Debian Codegraph @

js/src/builtin/Array.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "builtin/Array-inl.h"
8
9 #include "mozilla/CheckedInt.h"
10 #include "mozilla/DebugOnly.h"
11 #include "mozilla/MathAlgorithms.h"
12 #include "mozilla/Maybe.h"
13 #include "mozilla/ScopeExit.h"
14 #include "mozilla/SIMD.h"
15 #include "mozilla/TextUtils.h"
16
17 #include <algorithm>
18 #include <cmath>
19 #include <iterator>
20
21 #include "jsfriendapi.h"
22 #include "jsnum.h"
23 #include "jstypes.h"
24
25 #include "builtin/SelfHostingDefines.h"
26 #include "ds/Sort.h"
27 #include "jit/InlinableNatives.h"
28 #include "jit/TrampolineNatives.h"
29 #include "js/Class.h"
30 #include "js/Conversions.h"
31 #include "js/experimental/JitInfo.h" // JSJitGetterOp, JSJitInfo
32 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
33 #include "js/PropertySpec.h"
34 #include "util/Poison.h"
35 #include "util/StringBuilder.h"
36 #include "util/Text.h"
37 #include "vm/ArgumentsObject.h"
38 #include "vm/EqualityOperations.h"
39 #include "vm/Interpreter.h"
40 #include "vm/Iteration.h"
41 #include "vm/JSContext.h"
42 #include "vm/JSFunction.h"
43 #include "vm/JSObject.h"
44 #include "vm/PlainObject.h" // js::PlainObject
45 #include "vm/Probes.h"
46 #include "vm/SelfHosting.h"
47 #include "vm/Shape.h"
48 #include "vm/StringType.h"
49 #include "vm/ToSource.h" // js::ValueToSource
50 #include "vm/TypedArrayObject.h"
51 #include "vm/WrapperObject.h"
52 #include "builtin/Sorting-inl.h"
53 #include "vm/ArgumentsObject-inl.h"
54 #include "vm/ArrayObject-inl.h"
55 #include "vm/GeckoProfiler-inl.h"
56 #include "vm/IsGivenTypeObject-inl.h"
57 #include "vm/JSAtomUtils-inl.h" // PrimitiveValueToId, IndexToId
58 #include "vm/NativeObject-inl.h"
59
60 using namespace js;
61
62 using mozilla::Abs;
63 using mozilla::CeilingLog2;
64 using mozilla::CheckedInt;
65 using mozilla::DebugOnly;
66 using mozilla::Maybe;
67 using mozilla::SIMD;
68
69 using JS::AutoCheckCannotGC;
70 using JS::IsArrayAnswer;
71 using JS::ToUint32;
72
73 bool js::ObjectMayHaveExtraIndexedOwnProperties(JSObject* obj) {
74 if (!obj->is<NativeObject>()) {
75 return true;
76 }
77
78 if (obj->as<NativeObject>().isIndexed()) {
79 return true;
80 }
81
82 if (obj->is<TypedArrayObject>()) {
83 return true;
84 }
85
86 return ClassMayResolveId(*obj->runtimeFromAnyThread()->commonNames,
87 obj->getClass(), PropertyKey::Int(0), obj);
88 }
89
90 bool js::PrototypeMayHaveIndexedProperties(NativeObject* obj) {
91 do {
92 MOZ_ASSERT(obj->hasStaticPrototype(),
93 "dynamic-prototype objects must be non-native");
94
95 JSObject* proto = obj->staticPrototype();
96 if (!proto) {
97 return false; // no extra indexed properties found
98 }
99
100 if (ObjectMayHaveExtraIndexedOwnProperties(proto)) {
101 return true;
102 }
103 obj = &proto->as<NativeObject>();
104 if (obj->getDenseInitializedLength() != 0) {
105 return true;
106 }
107 } while (true);
108 }
109
110 /*
111 * Whether obj may have indexed properties anywhere besides its dense
112 * elements. This includes other indexed properties in its shape hierarchy, and
113 * indexed properties or elements along its prototype chain.
114 */
115 bool js::ObjectMayHaveExtraIndexedProperties(JSObject* obj) {
116 MOZ_ASSERT_IF(obj->hasDynamicPrototype(), !obj->is<NativeObject>());
117
118 if (ObjectMayHaveExtraIndexedOwnProperties(obj)) {
119 return true;
120 }
121
122 return PrototypeMayHaveIndexedProperties(&obj->as<NativeObject>());
123 }
124
125 bool JS::IsArray(JSContext* cx, HandleObject obj, IsArrayAnswer* answer) {
126 if (obj->is<ArrayObject>()) {
127 *answer = IsArrayAnswer::Array;
128 return true;
129 }
130
131 if (obj->is<ProxyObject>()) {
132 return Proxy::isArray(cx, obj, answer);
133 }
134
135 *answer = IsArrayAnswer::NotArray;
136 return true;
137 }
138
139 bool JS::IsArray(JSContext* cx, HandleObject obj, bool* isArray) {
140 IsArrayAnswer answer;
141 if (!IsArray(cx, obj, &answer)) {
142 return false;
143 }
144
145 if (answer == IsArrayAnswer::RevokedProxy) {
146 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
147 JSMSG_PROXY_REVOKED);
148 return false;
149 }
150
151 *isArray = answer == IsArrayAnswer::Array;
152 return true;
153 }
154
155 bool js::IsArrayFromJit(JSContext* cx, HandleObject obj, bool* isArray) {
156 return JS::IsArray(cx, obj, isArray);
157 }
158
159 // ES2017 7.1.15 ToLength.
160 bool js::ToLength(JSContext* cx, HandleValue v, uint64_t* out) {
161 if (v.isInt32()) {
162 int32_t i = v.toInt32();
163 *out = i < 0 ? 0 : i;
164 return true;
165 }
166
167 double d;
168 if (v.isDouble()) {
169 d = v.toDouble();
170 } else {
171 if (!ToNumber(cx, v, &d)) {
172 return false;
173 }
174 }
175
176 d = JS::ToInteger(d);
177 if (d <= 0.0) {
178 *out = 0;
179 } else {
180 *out = uint64_t(std::min(d, DOUBLE_INTEGRAL_PRECISION_LIMIT - 1));
181 }
182 return true;
183 }
184
185 bool js::GetLengthProperty(JSContext* cx, HandleObject obj, uint64_t* lengthp) {
186 if (obj->is<ArrayObject>()) {
187 *lengthp = obj->as<ArrayObject>().length();
188 return true;
189 }
190
191 if (obj->is<ArgumentsObject>()) {
192 ArgumentsObject& argsobj = obj->as<ArgumentsObject>();
193 if (!argsobj.hasOverriddenLength()) {
194 *lengthp = argsobj.initialLength();
195 return true;
196 }
197 }
198
199 RootedValue value(cx);
200 if (!GetProperty(cx, obj, obj, cx->names().length, &value)) {
201 return false;
202 }
203
204 return ToLength(cx, value, lengthp);
205 }
206
207 // Fast path for array functions where the object is expected to be an array.
208 static MOZ_ALWAYS_INLINE bool GetLengthPropertyInlined(JSContext* cx,
209 HandleObject obj,
210 uint64_t* lengthp) {
211 if (obj->is<ArrayObject>()) {
212 *lengthp = obj->as<ArrayObject>().length();
213 return true;
214 }
215
216 return GetLengthProperty(cx, obj, lengthp);
217 }
218
219 /*
220 * Determine if the id represents an array index.
221 *
222 * An id is an array index according to ECMA by (15.4):
223 *
224 * "Array objects give special treatment to a certain class of property names.
225 * A property name P (in the form of a string value) is an array index if and
226 * only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
227 * to 2^32-1."
228 *
229 * This means the largest allowed index is actually 2^32-2 (4294967294).
230 *
231 * In our implementation, it would be sufficient to check for id.isInt32()
232 * except that by using signed 31-bit integers we miss the top half of the
233 * valid range. This function checks the string representation itself; note
234 * that calling a standard conversion routine might allow strings such as
235 * "08" or "4.0" as array indices, which they are not.
236 *
237 */
238 JS_PUBLIC_API bool js::StringIsArrayIndex(const JSLinearString* str,
239 uint32_t* indexp) {
240 if (!str->isIndex(indexp)) {
241 return false;
242 }
243 MOZ_ASSERT(*indexp <= MAX_ARRAY_INDEX);
244 return true;
245 }
246
247 JS_PUBLIC_API bool js::StringIsArrayIndex(const char16_t* str, uint32_t length,
248 uint32_t* indexp) {
249 if (length == 0 || length > UINT32_CHAR_BUFFER_LENGTH) {
250 return false;
251 }
252 if (!mozilla::IsAsciiDigit(str[0])) {
253 return false;
254 }
255 if (!CheckStringIsIndex(str, length, indexp)) {
256 return false;
257 }
258 MOZ_ASSERT(*indexp <= MAX_ARRAY_INDEX);
259 return true;
260 }
261
262 template <typename T>
263 static bool ToId(JSContext* cx, T index, MutableHandleId id);
264
265 template <>
266 bool ToId(JSContext* cx, uint32_t index, MutableHandleId id) {
267 return IndexToId(cx, index, id);
268 }
269
270 template <>
271 bool ToId(JSContext* cx, uint64_t index, MutableHandleId id) {
272 MOZ_ASSERT(index < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
273
274 if (index == uint32_t(index)) {
275 return IndexToId(cx, uint32_t(index), id);
276 }
277
278 Value tmp = DoubleValue(index);
279 return PrimitiveValueToId<CanGC>(cx, HandleValue::fromMarkedLocation(&tmp),
280 id);
281 }
282
283 /*
284 * If the property at the given index exists, get its value into |vp| and set
285 * |*hole| to false. Otherwise set |*hole| to true and |vp| to Undefined.
286 */
287 template <typename T>
288 static bool HasAndGetElement(JSContext* cx, HandleObject obj,
289 HandleObject receiver, T index, bool* hole,
290 MutableHandleValue vp) {
291 if (obj->is<NativeObject>()) {
292 NativeObject* nobj = &obj->as<NativeObject>();
293 if (index < nobj->getDenseInitializedLength()) {
294 vp.set(nobj->getDenseElement(size_t(index)));
295 if (!vp.isMagic(JS_ELEMENTS_HOLE)) {
296 *hole = false;
297 return true;
298 }
299 }
300 if (nobj->is<ArgumentsObject>() && index <= UINT32_MAX) {
301 if (nobj->as<ArgumentsObject>().maybeGetElement(uint32_t(index), vp)) {
302 *hole = false;
303 return true;
304 }
305 }
306 }
307
308 RootedId id(cx);
309 if (!ToId(cx, index, &id)) {
310 return false;
311 }
312
313 bool found;
314 if (!HasProperty(cx, obj, id, &found)) {
315 return false;
316 }
317
318 if (found) {
319 if (!GetProperty(cx, obj, receiver, id, vp)) {
320 return false;
321 }
322 } else {
323 vp.setUndefined();
324 }
325 *hole = !found;
326 return true;
327 }
328
329 template <typename T>
330 static inline bool HasAndGetElement(JSContext* cx, HandleObject obj, T index,
331 bool* hole, MutableHandleValue vp) {
332 return HasAndGetElement(cx, obj, obj, index, hole, vp);
333 }
334
335 bool ElementAdder::append(JSContext* cx, HandleValue v) {
336 MOZ_ASSERT(index_ < length_);
337 if (resObj_) {
338 NativeObject* resObj = &resObj_->as<NativeObject>();
339 DenseElementResult result =
340 resObj->setOrExtendDenseElements(cx, index_, v.address(), 1);
341 if (result == DenseElementResult::Failure) {
342 return false;
343 }
344 if (result == DenseElementResult::Incomplete) {
345 if (!DefineDataElement(cx, resObj_, index_, v)) {
346 return false;
347 }
348 }
349 } else {
350 vp_[index_] = v;
351 }
352 index_++;
353 return true;
354 }
355
356 void ElementAdder::appendHole() {
357 MOZ_ASSERT(getBehavior_ == ElementAdder::CheckHasElemPreserveHoles);
358 MOZ_ASSERT(index_ < length_);
359 if (!resObj_) {
360 vp_[index_].setMagic(JS_ELEMENTS_HOLE);
361 }
362 index_++;
363 }
364
365 bool js::GetElementsWithAdder(JSContext* cx, HandleObject obj,
366 HandleObject receiver, uint32_t begin,
367 uint32_t end, ElementAdder* adder) {
368 MOZ_ASSERT(begin <= end);
369
370 RootedValue val(cx);
371 for (uint32_t i = begin; i < end; i++) {
372 if (adder->getBehavior() == ElementAdder::CheckHasElemPreserveHoles) {
373 bool hole;
374 if (!HasAndGetElement(cx, obj, receiver, i, &hole, &val)) {
375 return false;
376 }
377 if (hole) {
378 adder->appendHole();
379 continue;
380 }
381 } else {
382 MOZ_ASSERT(adder->getBehavior() == ElementAdder::GetElement);
383 if (!GetElement(cx, obj, receiver, i, &val)) {
384 return false;
385 }
386 }
387 if (!adder->append(cx, val)) {
388 return false;
389 }
390 }
391
392 return true;
393 }
394
395 static inline bool IsPackedArrayOrNoExtraIndexedProperties(JSObject* obj,
396 uint64_t length) {
397 return (IsPackedArray(obj) && obj->as<ArrayObject>().length() == length) ||
398 !ObjectMayHaveExtraIndexedProperties(obj);
399 }
400
401 static bool GetDenseElements(NativeObject* aobj, uint32_t length, Value* vp) {
402 MOZ_ASSERT(IsPackedArrayOrNoExtraIndexedProperties(aobj, length));
403
404 if (length > aobj->getDenseInitializedLength()) {
405 return false;
406 }
407
408 for (size_t i = 0; i < length; i++) {
409 vp[i] = aobj->getDenseElement(i);
410
411 // No other indexed properties so hole => undefined.
412 if (vp[i].isMagic(JS_ELEMENTS_HOLE)) {
413 vp[i] = UndefinedValue();
414 }
415 }
416
417 return true;
418 }
419
420 bool js::GetElements(JSContext* cx, HandleObject aobj, uint32_t length,
421 Value* vp) {
422 if (IsPackedArrayOrNoExtraIndexedProperties(aobj, length)) {
423 if (GetDenseElements(&aobj->as<NativeObject>(), length, vp)) {
424 return true;
425 }
426 }
427
428 if (aobj->is<ArgumentsObject>()) {
429 ArgumentsObject& argsobj = aobj->as<ArgumentsObject>();
430 if (!argsobj.hasOverriddenLength()) {
431 if (argsobj.maybeGetElements(0, length, vp)) {
432 return true;
433 }
434 }
435 }
436
437 if (aobj->is<TypedArrayObject>()) {
438 Handle<TypedArrayObject*> typedArray = aobj.as<TypedArrayObject>();
439 if (typedArray->length().valueOr(0) == length) {
440 return TypedArrayObject::getElements(cx, typedArray, length, vp);
441 }
442 }
443
444 if (js::GetElementsOp op = aobj->getOpsGetElements()) {
445 ElementAdder adder(cx, vp, length, ElementAdder::GetElement);
446 return op(cx, aobj, 0, length, &adder);
447 }
448
449 for (uint32_t i = 0; i < length; i++) {
450 if (!GetElement(cx, aobj, aobj, i,
451 MutableHandleValue::fromMarkedLocation(&vp[i]))) {
452 return false;
453 }
454 }
455
456 return true;
457 }
458
459 static inline bool GetArrayElement(JSContext* cx, HandleObject obj,
460 uint64_t index, MutableHandleValue vp) {
461 if (obj->is<NativeObject>()) {
462 NativeObject* nobj = &obj->as<NativeObject>();
463 if (index < nobj->getDenseInitializedLength()) {
464 vp.set(nobj->getDenseElement(size_t(index)));
465 if (!vp.isMagic(JS_ELEMENTS_HOLE)) {
466 return true;
467 }
468 }
469
470 if (nobj->is<ArgumentsObject>() && index <= UINT32_MAX) {
471 if (nobj->as<ArgumentsObject>().maybeGetElement(uint32_t(index), vp)) {
472 return true;
473 }
474 }
475 }
476
477 RootedId id(cx);
478 if (!ToId(cx, index, &id)) {
479 return false;
480 }
481 return GetProperty(cx, obj, obj, id, vp);
482 }
483
484 static inline bool DefineArrayElement(JSContext* cx, HandleObject obj,
485 uint64_t index, HandleValue value) {
486 RootedId id(cx);
487 if (!ToId(cx, index, &id)) {
488 return false;
489 }
490 return DefineDataProperty(cx, obj, id, value);
491 }
492
493 // Set the value of the property at the given index to v.
494 static inline bool SetArrayElement(JSContext* cx, HandleObject obj,
495 uint64_t index, HandleValue v) {
496 RootedId id(cx);
497 if (!ToId(cx, index, &id)) {
498 return false;
499 }
500
501 return SetProperty(cx, obj, id, v);
502 }
503
504 /*
505 * Attempt to delete the element |index| from |obj| as if by
506 * |obj.[[Delete]](index)|.
507 *
508 * If an error occurs while attempting to delete the element (that is, the call
509 * to [[Delete]] threw), return false.
510 *
511 * Otherwise call result.succeed() or result.fail() to indicate whether the
512 * deletion attempt succeeded (that is, whether the call to [[Delete]] returned
513 * true or false). (Deletes generally fail only when the property is
514 * non-configurable, but proxies may implement different semantics.)
515 */
516 static bool DeleteArrayElement(JSContext* cx, HandleObject obj, uint64_t index,
517 ObjectOpResult& result) {
518 if (obj->is<ArrayObject>() && !obj->as<NativeObject>().isIndexed() &&
519 !obj->as<NativeObject>().denseElementsAreSealed()) {
520 ArrayObject* aobj = &obj->as<ArrayObject>();
521 if (index <= UINT32_MAX) {
522 uint32_t idx = uint32_t(index);
523 if (idx < aobj->getDenseInitializedLength()) {
524 if (idx + 1 == aobj->getDenseInitializedLength()) {
525 aobj->setDenseInitializedLengthMaybeNonExtensible(cx, idx);
526 } else {
527 aobj->setDenseElementHole(idx);
528 }
529 if (!SuppressDeletedElement(cx, obj, idx)) {
530 return false;
531 }
532 }
533 }
534
535 return result.succeed();
536 }
537
538 RootedId id(cx);
539 if (!ToId(cx, index, &id)) {
540 return false;
541 }
542 return DeleteProperty(cx, obj, id, result);
543 }
544
545 /* ES6 draft rev 32 (2 Febr 2015) 7.3.7 */
546 static bool DeletePropertyOrThrow(JSContext* cx, HandleObject obj,
547 uint64_t index) {
548 ObjectOpResult success;
549 if (!DeleteArrayElement(cx, obj, index, success)) {
550 return false;
551 }
552 if (!success) {
553 RootedId id(cx);
554 if (!ToId(cx, index, &id)) {
555 return false;
556 }
557 return success.reportError(cx, obj, id);
558 }
559 return true;
560 }
561
562 static bool DeletePropertiesOrThrow(JSContext* cx, HandleObject obj,
563 uint64_t len, uint64_t finalLength) {
564 if (obj->is<ArrayObject>() && !obj->as<NativeObject>().isIndexed() &&
565 !obj->as<NativeObject>().denseElementsAreSealed()) {
566 if (len <= UINT32_MAX) {
567 // Skip forward to the initialized elements of this array.
568 len = std::min(uint32_t(len),
569 obj->as<ArrayObject>().getDenseInitializedLength());
570 }
571 }
572
573 for (uint64_t k = len; k > finalLength; k--) {
574 if (!CheckForInterrupt(cx)) {
575 return false;
576 }
577
578 if (!DeletePropertyOrThrow(cx, obj, k - 1)) {
579 return false;
580 }
581 }
582 return true;
583 }
584
585 static bool SetArrayLengthProperty(JSContext* cx, Handle<ArrayObject*> obj,
586 HandleValue value) {
587 RootedId id(cx, NameToId(cx->names().length));
588 ObjectOpResult result;
589 if (obj->lengthIsWritable()) {
590 Rooted<PropertyDescriptor> desc(
591 cx, PropertyDescriptor::Data(value, JS::PropertyAttribute::Writable));
592 if (!ArraySetLength(cx, obj, id, desc, result)) {
593 return false;
594 }
595 } else {
596 MOZ_ALWAYS_TRUE(result.fail(JSMSG_READ_ONLY));
597 }
598 return result.checkStrict(cx, obj, id);
599 }
600
601 static bool SetLengthProperty(JSContext* cx, HandleObject obj,
602 uint64_t length) {
603 MOZ_ASSERT(length < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
604
605 RootedValue v(cx, NumberValue(length));
606 if (obj->is<ArrayObject>()) {
607 return SetArrayLengthProperty(cx, obj.as<ArrayObject>(), v);
608 }
609 return SetProperty(cx, obj, cx->names().length, v);
610 }
611
612 bool js::SetLengthProperty(JSContext* cx, HandleObject obj, uint32_t length) {
613 RootedValue v(cx, NumberValue(length));
614 if (obj->is<ArrayObject>()) {
615 return SetArrayLengthProperty(cx, obj.as<ArrayObject>(), v);
616 }
617 return SetProperty(cx, obj, cx->names().length, v);
618 }
619
620 bool js::ArrayLengthGetter(JSContext* cx, HandleObject obj, HandleId id,
621 MutableHandleValue vp) {
622 MOZ_ASSERT(id == NameToId(cx->names().length));
623
624 vp.setNumber(obj->as<ArrayObject>().length());
625 return true;
626 }
627
628 bool js::ArrayLengthSetter(JSContext* cx, HandleObject obj, HandleId id,
629 HandleValue v, ObjectOpResult& result) {
630 MOZ_ASSERT(id == NameToId(cx->names().length));
631
632 Handle<ArrayObject*> arr = obj.as<ArrayObject>();
633 MOZ_ASSERT(arr->lengthIsWritable(),
634 "setter shouldn't be called if property is non-writable");
635
636 Rooted<PropertyDescriptor> desc(
637 cx, PropertyDescriptor::Data(v, JS::PropertyAttribute::Writable));
638 return ArraySetLength(cx, arr, id, desc, result);
639 }
640
641 struct ReverseIndexComparator {
642 bool operator()(const uint32_t& a, const uint32_t& b, bool* lessOrEqualp) {
643 MOZ_ASSERT(a != b, "how'd we get duplicate indexes?");
644 *lessOrEqualp = b <= a;
645 return true;
646 }
647 };
648
649 // Fast path to remove all elements with index >= newLen when setting the
650 // .length property of an array to a smaller value.
651 static bool TryFastDeleteElementsForNewLength(JSContext* cx,
652 Handle<ArrayObject*> arr,
653 uint32_t newLen, bool* success) {
654 MOZ_ASSERT(newLen < arr->length());
655
656 // If there might be an active for-in iterator for this array we have to use
657 // the generic code path because it supports suppressing deleted properties.
658 // Keys deleted before being reached during the iteration must not be visited.
659 if (arr->denseElementsMaybeInIteration()) {
660 *success = false;
661 return true;
662 }
663
664 // Sealed elements are non-configurable and shouldn't be removed.
665 if (arr->denseElementsAreSealed()) {
666 *success = false;
667 return true;
668 }
669
670 if (arr->isIndexed()) {
671 // This fast path doesn't suppress deleted properties from active iterators.
672 if (arr->compartment()->objectMaybeInIteration(arr)) {
673 *success = false;
674 return true;
675 }
676
677 // First add all sparse indexes we want to remove to a vector and check for
678 // non-configurable elements.
679 JS::RootedVector<PropertyKey> keys(cx);
680 for (ShapePropertyIter<NoGC> iter(arr->shape()); !iter.done(); iter++) {
681 uint32_t index;
682 if (!IdIsIndex(iter->key(), &index)) {
683 continue;
684 }
685 if (index < newLen) {
686 continue;
687 }
688 // Non-configurable elements shouldn't be removed.
689 if (!iter->configurable()) {
690 *success = false;
691 return true;
692 }
693 if (!keys.append(iter->key())) {
694 return false;
695 }
696 }
697
698 // Remove the sparse elements. Note that this starts at the most recently
699 // added property because this is most efficient when removing many
700 // elements.
701 //
702 // The rest of this function must be infallible (other than OOM).
703 for (size_t i = 0, len = keys.length(); i < len; i++) {
704 MOZ_ASSERT(arr->containsPure(keys[i]), "must still be a sparse element");
705 if (!NativeObject::removeProperty(cx, arr, keys[i])) {
706 MOZ_ASSERT(cx->isThrowingOutOfMemory());
707 return false;
708 }
709 }
710 }
711
712 // Remove dense elements.
713 uint32_t oldCapacity = arr->getDenseCapacity();
714 uint32_t oldInitializedLength = arr->getDenseInitializedLength();
715 MOZ_ASSERT(oldCapacity >= oldInitializedLength);
716 if (oldInitializedLength > newLen) {
717 arr->setDenseInitializedLengthMaybeNonExtensible(cx, newLen);
718 }
719 if (oldCapacity > newLen) {
720 if (arr->isExtensible()) {
721 arr->shrinkElements(cx, newLen);
722 } else {
723 MOZ_ASSERT(arr->getDenseInitializedLength() == arr->getDenseCapacity());
724 }
725 }
726
727 *success = true;
728 return true;
729 }
730
731 /* ES6 draft rev 34 (2015 Feb 20) 9.4.2.4 ArraySetLength */
732 bool js::ArraySetLength(JSContext* cx, Handle<ArrayObject*> arr, HandleId id,
733 Handle<PropertyDescriptor> desc,
734 ObjectOpResult& result) {
735 MOZ_ASSERT(id == NameToId(cx->names().length));
736 MOZ_ASSERT(desc.isDataDescriptor() || desc.isGenericDescriptor());
737
738 // Step 1.
739 uint32_t newLen;
740 if (!desc.hasValue()) {
741 // The spec has us calling OrdinaryDefineOwnProperty if
742 // Desc.[[Value]] is absent, but our implementation is so different that
743 // this is impossible. Instead, set newLen to the current length and
744 // proceed to step 9.
745 newLen = arr->length();
746 } else {
747 // Step 2 is irrelevant in our implementation.
748
749 // Step 3.
750 if (!ToUint32(cx, desc.value(), &newLen)) {
751 return false;
752 }
753
754 // Step 4.
755 double d;
756 if (!ToNumber(cx, desc.value(), &d)) {
757 return false;
758 }
759
760 // Step 5.
761 if (d != newLen) {
762 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
763 JSMSG_BAD_ARRAY_LENGTH);
764 return false;
765 }
766
767 // Steps 6-8 are irrelevant in our implementation.
768 }
769
770 // Steps 9-11.
771 bool lengthIsWritable = arr->lengthIsWritable();
772 #ifdef DEBUG
773 {
774 mozilla::Maybe<PropertyInfo> lengthProp = arr->lookupPure(id);
775 MOZ_ASSERT(lengthProp.isSome());
776 MOZ_ASSERT(lengthProp->writable() == lengthIsWritable);
777 }
778 #endif
779 uint32_t oldLen = arr->length();
780
781 // Part of steps 1.a, 12.a, and 16: Fail if we're being asked to change
782 // enumerability or configurability, or otherwise break the object
783 // invariants. (ES6 checks these by calling OrdinaryDefineOwnProperty, but
784 // in SM, the array length property is hardly ordinary.)
785 if ((desc.hasConfigurable() && desc.configurable()) ||
786 (desc.hasEnumerable() && desc.enumerable()) ||
787 (!lengthIsWritable && desc.hasWritable() && desc.writable())) {
788 return result.fail(JSMSG_CANT_REDEFINE_PROP);
789 }
790
791 // Steps 12-13 for arrays with non-writable length.
792 if (!lengthIsWritable) {
793 if (newLen == oldLen) {
794 return result.succeed();
795 }
796
797 return result.fail(JSMSG_CANT_REDEFINE_ARRAY_LENGTH);
798 }
799
800 // Step 19.
801 bool succeeded = true;
802 do {
803 // The initialized length and capacity of an array only need updating
804 // when non-hole elements are added or removed, which doesn't happen
805 // when array length stays the same or increases.
806 if (newLen >= oldLen) {
807 break;
808 }
809
810 bool success;
811 if (!TryFastDeleteElementsForNewLength(cx, arr, newLen, &success)) {
812 return false;
813 }
814
815 if (success) {
816 // We've done the work of deleting any elements needing deletion.
817 // Thus we can skip straight to defining the length.
818 break;
819 }
820
821 // Step 15.
822 //
823 // Attempt to delete all elements above the new length, from greatest
824 // to least. If any of these deletions fails, we're supposed to define
825 // the length to one greater than the index that couldn't be deleted,
826 // *with the property attributes specified*. This might convert the
827 // length to be not the value specified, yet non-writable. (You may be
828 // forgiven for thinking these are interesting semantics.) Example:
829 //
830 // var arr =
831 // Object.defineProperty([0, 1, 2, 3], 1, { writable: false });
832 // Object.defineProperty(arr, "length",
833 // { value: 0, writable: false });
834 //
835 // will convert |arr| to an array of non-writable length two, then
836 // throw a TypeError.
837 //
838 // We implement this behavior, in the relevant lops below, by setting
839 // |succeeded| to false. Then we exit the loop, define the length
840 // appropriately, and only then throw a TypeError, if necessary.
841 uint32_t gap = oldLen - newLen;
842 const uint32_t RemoveElementsFastLimit = 1 << 24;
843 if (gap < RemoveElementsFastLimit) {
844 // If we're removing a relatively small number of elements, just do
845 // it exactly by the spec.
846 while (newLen < oldLen) {
847 // Step 15a.
848 oldLen--;
849
850 // Steps 15b-d.
851 ObjectOpResult deleteSucceeded;
852 if (!DeleteElement(cx, arr, oldLen, deleteSucceeded)) {
853 return false;
854 }
855 if (!deleteSucceeded) {
856 newLen = oldLen + 1;
857 succeeded = false;
858 break;
859 }
860 }
861 } else {
862 // If we're removing a large number of elements from an array
863 // that's probably sparse, try a different tack. Get all the own
864 // property names, sift out the indexes in the deletion range into
865 // a vector, sort the vector greatest to least, then delete the
866 // indexes greatest to least using that vector. See bug 322135.
867 //
868 // This heuristic's kind of a huge guess -- "large number of
869 // elements" and "probably sparse" are completely unprincipled
870 // predictions. In the long run, bug 586842 will support the right
871 // fix: store sparse elements in a sorted data structure that
872 // permits fast in-reverse-order traversal and concurrent removals.
873
874 Vector<uint32_t> indexes(cx);
875 {
876 RootedIdVector props(cx);
877 if (!GetPropertyKeys(cx, arr, JSITER_OWNONLY | JSITER_HIDDEN, &props)) {
878 return false;
879 }
880
881 for (size_t i = 0; i < props.length(); i++) {
882 if (!CheckForInterrupt(cx)) {
883 return false;
884 }
885
886 uint32_t index;
887 if (!IdIsIndex(props[i], &index)) {
888 continue;
889 }
890
891 if (index >= newLen && index < oldLen) {
892 if (!indexes.append(index)) {
893 return false;
894 }
895 }
896 }
897 }
898
899 uint32_t count = indexes.length();
900 {
901 // We should use radix sort to be O(n), but this is uncommon
902 // enough that we'll punt til someone complains.
903 Vector<uint32_t> scratch(cx);
904 if (!scratch.resize(count)) {
905 return false;
906 }
907 MOZ_ALWAYS_TRUE(MergeSort(indexes.begin(), count, scratch.begin(),
908 ReverseIndexComparator()));
909 }
910
911 uint32_t index = UINT32_MAX;
912 for (uint32_t i = 0; i < count; i++) {
913 MOZ_ASSERT(indexes[i] < index, "indexes should never repeat");
914 index = indexes[i];
915
916 // Steps 15b-d.
917 ObjectOpResult deleteSucceeded;
918 if (!DeleteElement(cx, arr, index, deleteSucceeded)) {
919 return false;
920 }
921 if (!deleteSucceeded) {
922 newLen = index + 1;
923 succeeded = false;
924 break;
925 }
926 }
927 }
928 } while (false);
929
930 // Update array length. Technically we should have been doing this
931 // throughout the loop, in step 19.d.iii.
932 arr->setLength(cx, newLen);
933
934 // Step 20.
935 if (desc.hasWritable() && !desc.writable()) {
936 Maybe<PropertyInfo> lengthProp = arr->lookup(cx, id);
937 MOZ_ASSERT(lengthProp.isSome());
938 MOZ_ASSERT(lengthProp->isCustomDataProperty());
939 PropertyFlags flags = lengthProp->flags();
940 flags.clearFlag(PropertyFlag::Writable);
941 if (!NativeObject::changeCustomDataPropAttributes(cx, arr, id, flags)) {
942 return false;
943 }
944 }
945
946 // All operations past here until the |!succeeded| code must be infallible,
947 // so that all element fields remain properly synchronized.
948
949 // Trim the initialized length, if needed, to preserve the <= length
950 // invariant. (Capacity was already reduced during element deletion, if
951 // necessary.)
952 ObjectElements* header = arr->getElementsHeader();
953 header->initializedLength = std::min(header->initializedLength, newLen);
954
955 if (!arr->isExtensible()) {
956 arr->shrinkCapacityToInitializedLength(cx);
957 }
958
959 if (desc.hasWritable() && !desc.writable()) {
960 arr->setNonWritableLength(cx);
961 }
962
963 if (!succeeded) {
964 return result.fail(JSMSG_CANT_TRUNCATE_ARRAY);
965 }
966
967 return result.succeed();
968 }
969
970 static bool array_addProperty(JSContext* cx, HandleObject obj, HandleId id,
971 HandleValue v) {
972 ArrayObject* arr = &obj->as<ArrayObject>();
973
974 uint32_t index;
975 if (!IdIsIndex(id, &index)) {
976 return true;
977 }
978
979 uint32_t length = arr->length();
980 if (index >= length) {
981 MOZ_ASSERT(arr->lengthIsWritable(),
982 "how'd this element get added if length is non-writable?");
983 arr->setLength(cx, index + 1);
984 }
985 return true;
986 }
987
988 static SharedShape* AddLengthProperty(JSContext* cx,
989 Handle<SharedShape*> shape) {
990 // Add the 'length' property for a newly created array shape.
991
992 MOZ_ASSERT(shape->propMapLength() == 0);
993 MOZ_ASSERT(shape->getObjectClass() == &ArrayObject::class_);
994
995 RootedId lengthId(cx, NameToId(cx->names().length));
996 constexpr PropertyFlags flags = {PropertyFlag::CustomDataProperty,
997 PropertyFlag::Writable};
998
999 Rooted<SharedPropMap*> map(cx, shape->propMap());
1000 uint32_t mapLength = shape->propMapLength();
1001 ObjectFlags objectFlags = shape->objectFlags();
1002
1003 if (!SharedPropMap::addCustomDataProperty(cx, &ArrayObject::class_, &map,
1004 &mapLength, lengthId, flags,
1005 &objectFlags)) {
1006 return nullptr;
1007 }
1008
1009 return SharedShape::getPropMapShape(cx, shape->base(), shape->numFixedSlots(),
1010 map, mapLength, objectFlags);
1011 }
1012
1013 bool js::IsArrayConstructor(const JSObject* obj) {
1014 // Note: this also returns true for cross-realm Array constructors in the
1015 // same compartment.
1016 return IsNativeFunction(obj, ArrayConstructor);
1017 }
1018
1019 static bool IsArrayConstructor(const Value& v) {
1020 return v.isObject() && IsArrayConstructor(&v.toObject());
1021 }
1022
1023 bool js::IsCrossRealmArrayConstructor(JSContext* cx, JSObject* obj,
1024 bool* result) {
1025 if (obj->is<WrapperObject>()) {
1026 obj = CheckedUnwrapDynamic(obj, cx);
1027 if (!obj) {
1028 ReportAccessDenied(cx);
1029 return false;
1030 }
1031 }
1032
1033 *result =
1034 IsArrayConstructor(obj) && obj->as<JSFunction>().realm() != cx->realm();
1035 return true;
1036 }
1037
1038 static MOZ_ALWAYS_INLINE bool HasBuiltinArraySpecies(ArrayObject* arr,
1039 JSContext* cx) {
1040 // Ensure `Array.prototype.constructor` and `Array[@@species]` haven't been
1041 // mutated.
1042 if (!cx->realm()->realmFuses.optimizeArraySpeciesFuse.intact()) {
1043 return false;
1044 }
1045
1046 // Ensure the array has `Array.prototype` as prototype and doesn't have an own
1047 // `constructor` property.
1048 //
1049 // Most arrays have the default array shape so we have a fast path for this
1050 // case.
1051 GlobalObject* global = cx->global();
1052 if (arr->shape() == global->maybeArrayShapeWithDefaultProto()) {
1053 return true;
1054 }
1055
1056 // Ensure the array's prototype is the actual Array.prototype.
1057 NativeObject* arrayProto = global->maybeGetArrayPrototype();
1058 if (!arrayProto || arr->staticPrototype() != arrayProto) {
1059 return false;
1060 }
1061
1062 // Fail if the array has an own `constructor` property.
1063 if (arr->containsPure(NameToId(cx->names().constructor))) {
1064 return false;
1065 }
1066
1067 return true;
1068 }
1069
1070 // Returns true iff we know for -sure- that it is definitely safe to use the
1071 // realm's array constructor.
1072 //
1073 // This function is conservative as it may return false for cases which
1074 // ultimately do use the array constructor.
1075 static MOZ_ALWAYS_INLINE bool IsArraySpecies(JSContext* cx,
1076 HandleObject origArray) {
1077 if (MOZ_UNLIKELY(origArray->is<ProxyObject>())) {
1078 if (origArray->getClass()->isDOMClass()) {
1079 #ifdef DEBUG
1080 // We assume DOM proxies never return true for IsArray.
1081 IsArrayAnswer answer;
1082 MOZ_ASSERT(Proxy::isArray(cx, origArray, &answer));
1083 MOZ_ASSERT(answer == IsArrayAnswer::NotArray);
1084 #endif
1085 return true;
1086 }
1087 return false;
1088 }
1089
1090 // 9.4.2.3 Step 4. Non-array objects always use the default constructor.
1091 if (!origArray->is<ArrayObject>()) {
1092 return true;
1093 }
1094
1095 if (HasBuiltinArraySpecies(&origArray->as<ArrayObject>(), cx)) {
1096 return true;
1097 }
1098
1099 Value ctor;
1100 if (!GetPropertyPure(cx, origArray, NameToId(cx->names().constructor),
1101 &ctor)) {
1102 return false;
1103 }
1104
1105 if (!IsArrayConstructor(ctor)) {
1106 return ctor.isUndefined();
1107 }
1108
1109 // 9.4.2.3 Step 6.c. Use the current realm's constructor if |ctor| is a
1110 // cross-realm Array constructor.
1111 if (cx->realm() != ctor.toObject().as<JSFunction>().realm()) {
1112 return true;
1113 }
1114
1115 jsid speciesId = PropertyKey::Symbol(cx->wellKnownSymbols().species);
1116 JSFunction* getter;
1117 if (!GetGetterPure(cx, &ctor.toObject(), speciesId, &getter)) {
1118 return false;
1119 }
1120
1121 if (!getter) {
1122 return false;
1123 }
1124
1125 return IsSelfHostedFunctionWithName(getter, cx->names().dollar_ArraySpecies_);
1126 }
1127
1128 bool js::intrinsic_CanOptimizeArraySpecies(JSContext* cx, unsigned argc,
1129 Value* vp) {
1130 CallArgs args = CallArgsFromVp(argc, vp);
1131 MOZ_ASSERT(args.length() == 1);
1132
1133 JSObject* obj = &args[0].toObject();
1134
1135 // Return `true` if this is a plain array with the original array shape and
1136 // an intact array-species fuse. This is the case for at least 98% of all
1137 // calls on Speedometer 3 and JetStream 2. This condition is also simple
1138 // enough to inline efficiently in JIT code.
1139 //
1140 // The shape check implies:
1141 // - The object is an array object.
1142 // - The array belongs to the current realm.
1143 // - The array has (the current realm's) `Array.prototype` as prototype.
1144 // - The array does not define an own `constructor` property.
1145 bool optimizable =
1146 obj->shape() == cx->global()->maybeArrayShapeWithDefaultProto() &&
1147 cx->realm()->realmFuses.optimizeArraySpeciesFuse.intact();
1148 args.rval().setBoolean(optimizable);
1149 return true;
1150 }
1151
1152 static bool ArraySpeciesCreate(JSContext* cx, HandleObject origArray,
1153 uint64_t length, MutableHandleObject arr) {
1154 MOZ_ASSERT(length < DOUBLE_INTEGRAL_PRECISION_LIMIT);
1155
1156 FixedInvokeArgs<2> args(cx);
1157
1158 args[0].setObject(*origArray);
1159 args[1].set(NumberValue(length));
1160
1161 RootedValue rval(cx);
1162 if (!CallSelfHostedFunction(cx, cx->names().ArraySpeciesCreate,
1163 UndefinedHandleValue, args, &rval)) {
1164 return false;
1165 }
1166
1167 MOZ_ASSERT(rval.isObject());
1168 arr.set(&rval.toObject());
1169 return true;
1170 }
1171
1172 JSString* js::ArrayToSource(JSContext* cx, HandleObject obj) {
1173 AutoCycleDetector detector(cx, obj);
1174 if (!detector.init()) {
1175 return nullptr;
1176 }
1177
1178 JSStringBuilder sb(cx);
1179
1180 if (detector.foundCycle()) {
1181 if (!sb.append("[]")) {
1182 return nullptr;
1183 }
1184 return sb.finishString();
1185 }
1186
1187 if (!sb.append('[')) {
1188 return nullptr;
1189 }
1190
1191 uint64_t length;
1192 if (!GetLengthPropertyInlined(cx, obj, &length)) {
1193 return nullptr;
1194 }
1195
1196 RootedValue elt(cx);
1197 for (uint64_t index = 0; index < length; index++) {
1198 bool hole;
1199 if (!CheckForInterrupt(cx) ||
1200 !HasAndGetElement(cx, obj, index, &hole, &elt)) {
1201 return nullptr;
1202 }
1203
1204 /* Get element's character string. */
1205 JSString* str;
1206 if (hole) {
1207 str = cx->runtime()->emptyString;
1208 } else {
1209 str = ValueToSource(cx, elt);
1210 if (!str) {
1211 return nullptr;
1212 }
1213 }
1214
1215 /* Append element to buffer. */
1216 if (!sb.append(str)) {
1217 return nullptr;
1218 }
1219 if (index + 1 != length) {
1220 if (!sb.append(", ")) {
1221 return nullptr;
1222 }
1223 } else if (hole) {
1224 if (!sb.append(',')) {
1225 return nullptr;
1226 }
1227 }
1228 }
1229
1230 /* Finalize the buffer. */
1231 if (!sb.append(']')) {
1232 return nullptr;
1233 }
1234
1235 return sb.finishString();
1236 }
1237
1238 static bool array_toSource(JSContext* cx, unsigned argc, Value* vp) {
1239 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "toSource");
1240 CallArgs args = CallArgsFromVp(argc, vp);
1241
1242 if (!args.thisv().isObject()) {
1243 ReportIncompatible(cx, args);
1244 return false;
1245 }
1246
1247 Rooted<JSObject*> obj(cx, &args.thisv().toObject());
1248
1249 JSString* str = ArrayToSource(cx, obj);
1250 if (!str) {
1251 return false;
1252 }
1253
1254 args.rval().setString(str);
1255 return true;
1256 }
1257
1258 template <typename SeparatorOp>
1259 static bool ArrayJoinDenseKernel(JSContext* cx, SeparatorOp sepOp,
1260 Handle<NativeObject*> obj, uint64_t length,
1261 StringBuilder& sb, uint32_t* numProcessed) {
1262 // This loop handles all elements up to initializedLength. If
1263 // length > initLength we rely on the second loop to add the
1264 // other elements.
1265 MOZ_ASSERT(*numProcessed == 0);
1266 uint64_t initLength =
1267 std::min<uint64_t>(obj->getDenseInitializedLength(), length);
1268 MOZ_ASSERT(initLength <= UINT32_MAX,
1269 "initialized length shouldn't exceed UINT32_MAX");
1270 uint32_t initLengthClamped = uint32_t(initLength);
1271 while (*numProcessed < initLengthClamped) {
1272 if (!CheckForInterrupt(cx)) {
1273 return false;
1274 }
1275
1276 // Step 7.b.
1277 Value elem = obj->getDenseElement(*numProcessed);
1278
1279 // Steps 7.c-d.
1280 if (elem.isString()) {
1281 if (!sb.append(elem.toString())) {
1282 return false;
1283 }
1284 } else if (elem.isNumber()) {
1285 if (!NumberValueToStringBuilder(elem, sb)) {
1286 return false;
1287 }
1288 } else if (elem.isBoolean()) {
1289 if (!BooleanToStringBuilder(elem.toBoolean(), sb)) {
1290 return false;
1291 }
1292 } else if (elem.isObject() || elem.isSymbol()) {
1293 /*
1294 * Object stringifying could modify the initialized length or make
1295 * the array sparse. Delegate it to a separate loop to keep this
1296 * one tight.
1297 *
1298 * Symbol stringifying is a TypeError, so into the slow path
1299 * with those as well.
1300 */
1301 break;
1302 } else if (elem.isBigInt()) {
1303 // ToString(bigint) doesn't access bigint.toString or
1304 // anything like that, so it can't mutate the array we're
1305 // walking through, so it *could* be handled here. We don't
1306 // do so yet for reasons of initial-implementation economy.
1307 break;
1308 } else {
1309 MOZ_ASSERT(elem.isMagic(JS_ELEMENTS_HOLE) || elem.isNullOrUndefined());
1310 }
1311
1312 // Steps 7.a, 7.e.
1313 if (++(*numProcessed) != length && !sepOp(sb)) {
1314 return false;
1315 }
1316 }
1317
1318 return true;
1319 }
1320
1321 template <typename SeparatorOp>
1322 static bool ArrayJoinKernel(JSContext* cx, SeparatorOp sepOp, HandleObject obj,
1323 uint64_t length, StringBuilder& sb) {
1324 // Step 6.
1325 uint32_t numProcessed = 0;
1326
1327 if (IsPackedArrayOrNoExtraIndexedProperties(obj, length)) {
1328 if (!ArrayJoinDenseKernel<SeparatorOp>(cx, sepOp, obj.as<NativeObject>(),
1329 length, sb, &numProcessed)) {
1330 return false;
1331 }
1332 }
1333
1334 // Step 7.
1335 if (numProcessed != length) {
1336 RootedValue v(cx);
1337 for (uint64_t i = numProcessed; i < length;) {
1338 if (!CheckForInterrupt(cx)) {
1339 return false;
1340 }
1341
1342 // Step 7.b.
1343 if (!GetArrayElement(cx, obj, i, &v)) {
1344 return false;
1345 }
1346
1347 // Steps 7.c-d.
1348 if (!v.isNullOrUndefined()) {
1349 if (!ValueToStringBuilder(cx, v, sb)) {
1350 return false;
1351 }
1352 }
1353
1354 // Steps 7.a, 7.e.
1355 if (++i != length && !sepOp(sb)) {
1356 return false;
1357 }
1358 }
1359 }
1360
1361 return true;
1362 }
1363
1364 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
1365 // 22.1.3.13 Array.prototype.join ( separator )
1366 bool js::array_join(JSContext* cx, unsigned argc, Value* vp) {
1367 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "join");
1368 CallArgs args = CallArgsFromVp(argc, vp);
1369
1370 // Step 1.
1371 RootedObject obj(cx, ToObject(cx, args.thisv()));
1372 if (!obj) {
1373 return false;
1374 }
1375
1376 AutoCycleDetector detector(cx, obj);
1377 if (!detector.init()) {
1378 return false;
1379 }
1380
1381 if (detector.foundCycle()) {
1382 args.rval().setString(cx->names().empty_);
1383 return true;
1384 }
1385
1386 // Step 2.
1387 uint64_t length;
1388 if (!GetLengthPropertyInlined(cx, obj, &length)) {
1389 return false;
1390 }
1391
1392 // Steps 3-4.
1393 Rooted<JSLinearString*> sepstr(cx);
1394 if (args.hasDefined(0)) {
1395 JSString* s = ToString<CanGC>(cx, args[0]);
1396 if (!s) {
1397 return false;
1398 }
1399 sepstr = s->ensureLinear(cx);
1400 if (!sepstr) {
1401 return false;
1402 }
1403 } else {
1404 sepstr = cx->names().comma_;
1405 }
1406
1407 // Steps 5-8 (When the length is zero, directly return the empty string).
1408 if (length == 0) {
1409 args.rval().setString(cx->emptyString());
1410 return true;
1411 }
1412
1413 // An optimized version of a special case of steps 5-8: when length==1 and
1414 // the 0th element is a string, ToString() of that element is a no-op and
1415 // so it can be immediately returned as the result.
1416 if (length == 1 && obj->is<NativeObject>()) {
1417 NativeObject* nobj = &obj->as<NativeObject>();
1418 if (nobj->getDenseInitializedLength() == 1) {
1419 Value elem0 = nobj->getDenseElement(0);
1420 if (elem0.isString()) {
1421 args.rval().set(elem0);
1422 return true;
1423 }
1424 }
1425 }
1426
1427 // Step 5.
1428 JSStringBuilder sb(cx);
1429 if (sepstr->hasTwoByteChars() && !sb.ensureTwoByteChars()) {
1430 return false;
1431 }
1432
1433 // The separator will be added |length - 1| times, reserve space for that
1434 // so that we don't have to unnecessarily grow the buffer.
1435 size_t seplen = sepstr->length();
1436 if (seplen > 0) {
1437 if (length > UINT32_MAX) {
1438 ReportAllocationOverflow(cx);
1439 return false;
1440 }
1441 CheckedInt<uint32_t> res =
1442 CheckedInt<uint32_t>(seplen) * (uint32_t(length) - 1);
1443 if (!res.isValid()) {
1444 ReportAllocationOverflow(cx);
1445 return false;
1446 }
1447
1448 if (!sb.reserve(res.value())) {
1449 return false;
1450 }
1451 }
1452
1453 // Various optimized versions of steps 6-7.
1454 if (seplen == 0) {
1455 auto sepOp = [](StringBuilder&) { return true; };
1456 if (!ArrayJoinKernel(cx, sepOp, obj, length, sb)) {
1457 return false;
1458 }
1459 } else if (seplen == 1) {
1460 char16_t c = sepstr->latin1OrTwoByteChar(0);
1461 if (c <= JSString::MAX_LATIN1_CHAR) {
1462 Latin1Char l1char = Latin1Char(c);
1463 auto sepOp = [l1char](StringBuilder& sb) { return sb.append(l1char); };
1464 if (!ArrayJoinKernel(cx, sepOp, obj, length, sb)) {
1465 return false;
1466 }
1467 } else {
1468 auto sepOp = [c](StringBuilder& sb) { return sb.append(c); };
1469 if (!ArrayJoinKernel(cx, sepOp, obj, length, sb)) {
1470 return false;
1471 }
1472 }
1473 } else {
1474 Handle<JSLinearString*> sepHandle = sepstr;
1475 auto sepOp = [sepHandle](StringBuilder& sb) {
1476 return sb.append(sepHandle);
1477 };
1478 if (!ArrayJoinKernel(cx, sepOp, obj, length, sb)) {
1479 return false;
1480 }
1481 }
1482
1483 // Step 8.
1484 JSString* str = sb.finishString();
1485 if (!str) {
1486 return false;
1487 }
1488
1489 args.rval().setString(str);
1490 return true;
1491 }
1492
1493 // ES2017 draft rev f8a9be8ea4bd97237d176907a1e3080dce20c68f
1494 // 22.1.3.27 Array.prototype.toLocaleString ([ reserved1 [ , reserved2 ] ])
1495 // ES2017 Intl draft rev 78bbe7d1095f5ff3760ac4017ed366026e4cb276
1496 // 13.4.1 Array.prototype.toLocaleString ([ locales [ , options ]])
1497 static bool array_toLocaleString(JSContext* cx, unsigned argc, Value* vp) {
1498 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype",
1499 "toLocaleString");
1500
1501 CallArgs args = CallArgsFromVp(argc, vp);
1502
1503 // Step 1
1504 RootedObject obj(cx, ToObject(cx, args.thisv()));
1505 if (!obj) {
1506 return false;
1507 }
1508
1509 // Avoid calling into self-hosted code if the array is empty.
1510 if (obj->is<ArrayObject>() && obj->as<ArrayObject>().length() == 0) {
1511 args.rval().setString(cx->names().empty_);
1512 return true;
1513 }
1514
1515 AutoCycleDetector detector(cx, obj);
1516 if (!detector.init()) {
1517 return false;
1518 }
1519
1520 if (detector.foundCycle()) {
1521 args.rval().setString(cx->names().empty_);
1522 return true;
1523 }
1524
1525 FixedInvokeArgs<2> args2(cx);
1526
1527 args2[0].set(args.get(0));
1528 args2[1].set(args.get(1));
1529
1530 // Steps 2-10.
1531 RootedValue thisv(cx, ObjectValue(*obj));
1532 return CallSelfHostedFunction(cx, cx->names().ArrayToLocaleString, thisv,
1533 args2, args.rval());
1534 }
1535
1536 /* vector must point to rooted memory. */
1537 static bool SetArrayElements(JSContext* cx, HandleObject obj, uint64_t start,
1538 uint32_t count, const Value* vector) {
1539 MOZ_ASSERT(count <= MAX_ARRAY_INDEX);
1540 MOZ_ASSERT(start + count < uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT));
1541
1542 if (count == 0) {
1543 return true;
1544 }
1545
1546 if (!ObjectMayHaveExtraIndexedProperties(obj) && start <= UINT32_MAX) {
1547 NativeObject* nobj = &obj->as<NativeObject>();
1548 DenseElementResult result =
1549 nobj->setOrExtendDenseElements(cx, uint32_t(start), vector, count);
1550 if (result != DenseElementResult::Incomplete) {
1551 return result == DenseElementResult::Success;
1552 }
1553 }
1554
1555 RootedId id(cx);
1556 const Value* end = vector + count;
1557 while (vector < end) {
1558 if (!CheckForInterrupt(cx)) {
1559 return false;
1560 }
1561
1562 if (!ToId(cx, start++, &id)) {
1563 return false;
1564 }
1565
1566 if (!SetProperty(cx, obj, id, HandleValue::fromMarkedLocation(vector++))) {
1567 return false;
1568 }
1569 }
1570
1571 return true;
1572 }
1573
1574 static DenseElementResult ArrayReverseDenseKernel(JSContext* cx,
1575 Handle<NativeObject*> obj,
1576 uint32_t length) {
1577 MOZ_ASSERT(length > 1);
1578
1579 // If there are no elements, we're done.
1580 if (obj->getDenseInitializedLength() == 0) {
1581 return DenseElementResult::Success;
1582 }
1583
1584 if (!obj->isExtensible()) {
1585 return DenseElementResult::Incomplete;
1586 }
1587
1588 if (!IsPackedArray(obj)) {
1589 /*
1590 * It's actually surprisingly complicated to reverse an array due
1591 * to the orthogonality of array length and array capacity while
1592 * handling leading and trailing holes correctly. Reversing seems
1593 * less likely to be a common operation than other array
1594 * mass-mutation methods, so for now just take a probably-small
1595 * memory hit (in the absence of too many holes in the array at
1596 * its start) and ensure that the capacity is sufficient to hold
1597 * all the elements in the array if it were full.
1598 */
1599 DenseElementResult result = obj->ensureDenseElements(cx, length, 0);
1600 if (result != DenseElementResult::Success) {
1601 return result;
1602 }
1603
1604 /* Fill out the array's initialized length to its proper length. */
1605 obj->ensureDenseInitializedLength(length, 0);
1606 }
1607
1608 if (!obj->denseElementsMaybeInIteration() &&
1609 !cx->zone()->needsIncrementalBarrier()) {
1610 obj->reverseDenseElementsNoPreBarrier(length);
1611 return DenseElementResult::Success;
1612 }
1613
1614 auto setElementMaybeHole = [](JSContext* cx, Handle<NativeObject*> obj,
1615 uint32_t index, const Value& val) {
1616 if (MOZ_LIKELY(!val.isMagic(JS_ELEMENTS_HOLE))) {
1617 obj->setDenseElement(index, val);
1618 return true;
1619 }
1620
1621 obj->setDenseElementHole(index);
1622 return SuppressDeletedProperty(cx, obj, PropertyKey::Int(index));
1623 };
1624
1625 RootedValue origlo(cx), orighi(cx);
1626
1627 uint32_t lo = 0, hi = length - 1;
1628 for (; lo < hi; lo++, hi--) {
1629 origlo = obj->getDenseElement(lo);
1630 orighi = obj->getDenseElement(hi);
1631 if (!setElementMaybeHole(cx, obj, lo, orighi)) {
1632 return DenseElementResult::Failure;
1633 }
1634 if (!setElementMaybeHole(cx, obj, hi, origlo)) {
1635 return DenseElementResult::Failure;
1636 }
1637 }
1638
1639 return DenseElementResult::Success;
1640 }
1641
1642 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
1643 // 22.1.3.21 Array.prototype.reverse ( )
1644 static bool array_reverse(JSContext* cx, unsigned argc, Value* vp) {
1645 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "reverse");
1646 CallArgs args = CallArgsFromVp(argc, vp);
1647
1648 // Step 1.
1649 RootedObject obj(cx, ToObject(cx, args.thisv()));
1650 if (!obj) {
1651 return false;
1652 }
1653
1654 // Step 2.
1655 uint64_t len;
1656 if (!GetLengthPropertyInlined(cx, obj, &len)) {
1657 return false;
1658 }
1659
1660 // An empty array or an array with length 1 is already reversed.
1661 if (len <= 1) {
1662 args.rval().setObject(*obj);
1663 return true;
1664 }
1665
1666 if (IsPackedArrayOrNoExtraIndexedProperties(obj, len) && len <= UINT32_MAX) {
1667 DenseElementResult result =
1668 ArrayReverseDenseKernel(cx, obj.as<NativeObject>(), uint32_t(len));
1669 if (result != DenseElementResult::Incomplete) {
1670 /*
1671 * Per ECMA-262, don't update the length of the array, even if the new
1672 * array has trailing holes (and thus the original array began with
1673 * holes).
1674 */
1675 args.rval().setObject(*obj);
1676 return result == DenseElementResult::Success;
1677 }
1678 }
1679
1680 // Steps 3-5.
1681 RootedValue lowval(cx), hival(cx);
1682 for (uint64_t i = 0, half = len / 2; i < half; i++) {
1683 bool hole, hole2;
1684 if (!CheckForInterrupt(cx) ||
1685 !HasAndGetElement(cx, obj, i, &hole, &lowval) ||
1686 !HasAndGetElement(cx, obj, len - i - 1, &hole2, &hival)) {
1687 return false;
1688 }
1689
1690 if (!hole && !hole2) {
1691 if (!SetArrayElement(cx, obj, i, hival)) {
1692 return false;
1693 }
1694 if (!SetArrayElement(cx, obj, len - i - 1, lowval)) {
1695 return false;
1696 }
1697 } else if (hole && !hole2) {
1698 if (!SetArrayElement(cx, obj, i, hival)) {
1699 return false;
1700 }
1701 if (!DeletePropertyOrThrow(cx, obj, len - i - 1)) {
1702 return false;
1703 }
1704 } else if (!hole && hole2) {
1705 if (!DeletePropertyOrThrow(cx, obj, i)) {
1706 return false;
1707 }
1708 if (!SetArrayElement(cx, obj, len - i - 1, lowval)) {
1709 return false;
1710 }
1711 } else {
1712 // No action required.
1713 }
1714 }
1715
1716 // Step 6.
1717 args.rval().setObject(*obj);
1718 return true;
1719 }
1720
1721 static inline bool CompareStringValues(JSContext* cx, const Value& a,
1722 const Value& b, bool* lessOrEqualp) {
1723 if (!CheckForInterrupt(cx)) {
1724 return false;
1725 }
1726
1727 JSString* astr = a.toString();
1728 JSString* bstr = b.toString();
1729 int32_t result;
1730 if (!CompareStrings(cx, astr, bstr, &result)) {
1731 return false;
1732 }
1733
1734 *lessOrEqualp = (result <= 0);
1735 return true;
1736 }
1737
1738 static const uint64_t powersOf10[] = {
1739 1, 10, 100, 1000, 10000, 100000,
1740 1000000, 10000000, 100000000, 1000000000, 1000000000000ULL};
1741
1742 static inline unsigned NumDigitsBase10(uint32_t n) {
1743 /*
1744 * This is just floor_log10(n) + 1
1745 * Algorithm taken from
1746 * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
1747 */
1748 uint32_t log2 = CeilingLog2(n);
1749 uint32_t t = log2 * 1233 >> 12;
1750 return t - (n < powersOf10[t]) + 1;
1751 }
1752
1753 static inline bool CompareLexicographicInt32(const Value& a, const Value& b,
1754 bool* lessOrEqualp) {
1755 int32_t aint = a.toInt32();
1756 int32_t bint = b.toInt32();
1757
1758 /*
1759 * If both numbers are equal ... trivial
1760 * If only one of both is negative --> arithmetic comparison as char code
1761 * of '-' is always less than any other digit
1762 * If both numbers are negative convert them to positive and continue
1763 * handling ...
1764 */
1765 if (aint == bint) {
1766 *lessOrEqualp = true;
1767 } else if ((aint < 0) && (bint >= 0)) {
1768 *lessOrEqualp = true;
1769 } else if ((aint >= 0) && (bint < 0)) {
1770 *lessOrEqualp = false;
1771 } else {
1772 uint32_t auint = Abs(aint);
1773 uint32_t buint = Abs(bint);
1774
1775 /*
1776 * ... get number of digits of both integers.
1777 * If they have the same number of digits --> arithmetic comparison.
1778 * If digits_a > digits_b: a < b*10e(digits_a - digits_b).
1779 * If digits_b > digits_a: a*10e(digits_b - digits_a) <= b.
1780 */
1781 unsigned digitsa = NumDigitsBase10(auint);
1782 unsigned digitsb = NumDigitsBase10(buint);
1783 if (digitsa == digitsb) {
1784 *lessOrEqualp = (auint <= buint);
1785 } else if (digitsa > digitsb) {
1786 MOZ_ASSERT((digitsa - digitsb) < std::size(powersOf10));
1787 *lessOrEqualp =
1788 (uint64_t(auint) < uint64_t(buint) * powersOf10[digitsa - digitsb]);
1789 } else { /* if (digitsb > digitsa) */
1790 MOZ_ASSERT((digitsb - digitsa) < std::size(powersOf10));
1791 *lessOrEqualp =
1792 (uint64_t(auint) * powersOf10[digitsb - digitsa] <= uint64_t(buint));
1793 }
1794 }
1795
1796 return true;
1797 }
1798
1799 template <typename Char1, typename Char2>
1800 static inline bool CompareSubStringValues(JSContext* cx, const Char1* s1,
1801 size_t len1, const Char2* s2,
1802 size_t len2, bool* lessOrEqualp) {
1803 if (!CheckForInterrupt(cx)) {
1804 return false;
1805 }
1806
1807 if (!s1 || !s2) {
1808 return false;
1809 }
1810
1811 int32_t result = CompareChars(s1, len1, s2, len2);
1812 *lessOrEqualp = (result <= 0);
1813 return true;
1814 }
1815
1816 namespace {
1817
1818 struct SortComparatorStrings {
1819 JSContext* const cx;
1820
1821 explicit SortComparatorStrings(JSContext* cx) : cx(cx) {}
1822
1823 bool operator()(const Value& a, const Value& b, bool* lessOrEqualp) {
1824 return CompareStringValues(cx, a, b, lessOrEqualp);
1825 }
1826 };
1827
1828 struct SortComparatorLexicographicInt32 {
1829 bool operator()(const Value& a, const Value& b, bool* lessOrEqualp) {
1830 return CompareLexicographicInt32(a, b, lessOrEqualp);
1831 }
1832 };
1833
1834 struct StringifiedElement {
1835 size_t charsBegin;
1836 size_t charsEnd;
1837 size_t elementIndex;
1838 };
1839
1840 struct SortComparatorStringifiedElements {
1841 JSContext* const cx;
1842 const StringBuilder& sb;
1843
1844 SortComparatorStringifiedElements(JSContext* cx, const StringBuilder& sb)
1845 : cx(cx), sb(sb) {}
1846
1847 bool operator()(const StringifiedElement& a, const StringifiedElement& b,
1848 bool* lessOrEqualp) {
1849 size_t lenA = a.charsEnd - a.charsBegin;
1850 size_t lenB = b.charsEnd - b.charsBegin;
1851
1852 if (sb.isUnderlyingBufferLatin1()) {
1853 return CompareSubStringValues(cx, sb.rawLatin1Begin() + a.charsBegin,
1854 lenA, sb.rawLatin1Begin() + b.charsBegin,
1855 lenB, lessOrEqualp);
1856 }
1857
1858 return CompareSubStringValues(cx, sb.rawTwoByteBegin() + a.charsBegin, lenA,
1859 sb.rawTwoByteBegin() + b.charsBegin, lenB,
1860 lessOrEqualp);
1861 }
1862 };
1863
1864 struct NumericElement {
1865 double dv;
1866 size_t elementIndex;
1867 };
1868
1869 static bool ComparatorNumericLeftMinusRight(const NumericElement& a,
1870 const NumericElement& b,
1871 bool* lessOrEqualp) {
1872 *lessOrEqualp = std::isunordered(a.dv, b.dv) || (a.dv <= b.dv);
1873 return true;
1874 }
1875
1876 static bool ComparatorNumericRightMinusLeft(const NumericElement& a,
1877 const NumericElement& b,
1878 bool* lessOrEqualp) {
1879 *lessOrEqualp = std::isunordered(a.dv, b.dv) || (b.dv <= a.dv);
1880 return true;
1881 }
1882
1883 using ComparatorNumeric = bool (*)(const NumericElement&, const NumericElement&,
1884 bool*);
1885
1886 static const ComparatorNumeric SortComparatorNumerics[] = {
1887 nullptr, nullptr, ComparatorNumericLeftMinusRight,
1888 ComparatorNumericRightMinusLeft};
1889
1890 static bool ComparatorInt32LeftMinusRight(const Value& a, const Value& b,
1891 bool* lessOrEqualp) {
1892 *lessOrEqualp = (a.toInt32() <= b.toInt32());
1893 return true;
1894 }
1895
1896 static bool ComparatorInt32RightMinusLeft(const Value& a, const Value& b,
1897 bool* lessOrEqualp) {
1898 *lessOrEqualp = (b.toInt32() <= a.toInt32());
1899 return true;
1900 }
1901
1902 using ComparatorInt32 = bool (*)(const Value&, const Value&, bool*);
1903
1904 static const ComparatorInt32 SortComparatorInt32s[] = {
1905 nullptr, nullptr, ComparatorInt32LeftMinusRight,
1906 ComparatorInt32RightMinusLeft};
1907
1908 // Note: Values for this enum must match up with SortComparatorNumerics
1909 // and SortComparatorInt32s.
1910 enum ComparatorMatchResult {
1911 Match_Failure = 0,
1912 Match_None,
1913 Match_LeftMinusRight,
1914 Match_RightMinusLeft
1915 };
1916
1917 } // namespace
1918
1919 /*
1920 * Specialize behavior for comparator functions with particular common bytecode
1921 * patterns: namely, |return x - y| and |return y - x|.
1922 */
1923 static ComparatorMatchResult MatchNumericComparator(JSContext* cx,
1924 JSObject* obj) {
1925 if (!obj->is<JSFunction>()) {
1926 return Match_None;
1927 }
1928
1929 RootedFunction fun(cx, &obj->as<JSFunction>());
1930 if (!fun->isInterpreted() || fun->isClassConstructor()) {
1931 return Match_None;
1932 }
1933
1934 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
1935 if (!script) {
1936 return Match_Failure;
1937 }
1938
1939 jsbytecode* pc = script->code();
1940
1941 uint16_t arg0, arg1;
1942 if (JSOp(*pc) != JSOp::GetArg) {
1943 return Match_None;
1944 }
1945 arg0 = GET_ARGNO(pc);
1946 pc += JSOpLength_GetArg;
1947
1948 if (JSOp(*pc) != JSOp::GetArg) {
1949 return Match_None;
1950 }
1951 arg1 = GET_ARGNO(pc);
1952 pc += JSOpLength_GetArg;
1953
1954 if (JSOp(*pc) != JSOp::Sub) {
1955 return Match_None;
1956 }
1957 pc += JSOpLength_Sub;
1958
1959 if (JSOp(*pc) != JSOp::Return) {
1960 return Match_None;
1961 }
1962
1963 if (arg0 == 0 && arg1 == 1) {
1964 return Match_LeftMinusRight;
1965 }
1966
1967 if (arg0 == 1 && arg1 == 0) {
1968 return Match_RightMinusLeft;
1969 }
1970
1971 return Match_None;
1972 }
1973
1974 template <typename K, typename C>
1975 static inline bool MergeSortByKey(K keys, size_t len, K scratch, C comparator,
1976 MutableHandle<GCVector<Value>> vec) {
1977 MOZ_ASSERT(vec.length() >= len);
1978
1979 /* Sort keys. */
1980 if (!MergeSort(keys, len, scratch, comparator)) {
1981 return false;
1982 }
1983
1984 /*
1985 * Reorder vec by keys in-place, going element by element. When an out-of-
1986 * place element is encountered, move that element to its proper position,
1987 * displacing whatever element was at *that* point to its proper position,
1988 * and so on until an element must be moved to the current position.
1989 *
1990 * At each outer iteration all elements up to |i| are sorted. If
1991 * necessary each inner iteration moves some number of unsorted elements
1992 * (including |i|) directly to sorted position. Thus on completion |*vec|
1993 * is sorted, and out-of-position elements have moved once. Complexity is
1994 * Θ(len) + O(len) == O(2*len), with each element visited at most twice.
1995 */
1996 for (size_t i = 0; i < len; i++) {
1997 size_t j = keys[i].elementIndex;
1998 if (i == j) {
1999 continue; // fixed point
2000 }
2001
2002 MOZ_ASSERT(j > i, "Everything less than |i| should be in the right place!");
2003 Value tv = vec[j];
2004 do {
2005 size_t k = keys[j].elementIndex;
2006 keys[j].elementIndex = j;
2007 vec[j].set(vec[k]);
2008 j = k;
2009 } while (j != i);
2010
2011 // We could assert the loop invariant that |i == keys[i].elementIndex|
2012 // here if we synced |keys[i].elementIndex|. But doing so would render
2013 // the assertion vacuous, so don't bother, even in debug builds.
2014 vec[i].set(tv);
2015 }
2016
2017 return true;
2018 }
2019
2020 /*
2021 * Sort Values as strings.
2022 *
2023 * To minimize #conversions, SortLexicographically() first converts all Values
2024 * to strings at once, then sorts the elements by these cached strings.
2025 */
2026 static bool SortLexicographically(JSContext* cx,
2027 MutableHandle<GCVector<Value>> vec,
2028 size_t len) {
2029 MOZ_ASSERT(vec.length() >= len);
2030
2031 StringBuilder sb(cx);
2032 Vector<StringifiedElement, 0, TempAllocPolicy> strElements(cx);
2033
2034 /* MergeSort uses the upper half as scratch space. */
2035 if (!strElements.resize(2 * len)) {
2036 return false;
2037 }
2038
2039 /* Convert Values to strings. */
2040 size_t cursor = 0;
2041 for (size_t i = 0; i < len; i++) {
2042 if (!CheckForInterrupt(cx)) {
2043 return false;
2044 }
2045
2046 if (!ValueToStringBuilder(cx, vec[i], sb)) {
2047 return false;
2048 }
2049
2050 strElements[i] = {cursor, sb.length(), i};
2051 cursor = sb.length();
2052 }
2053
2054 /* Sort Values in vec alphabetically. */
2055 return MergeSortByKey(strElements.begin(), len, strElements.begin() + len,
2056 SortComparatorStringifiedElements(cx, sb), vec);
2057 }
2058
2059 /*
2060 * Sort Values as numbers.
2061 *
2062 * To minimize #conversions, SortNumerically first converts all Values to
2063 * numerics at once, then sorts the elements by these cached numerics.
2064 */
2065 static bool SortNumerically(JSContext* cx, MutableHandle<GCVector<Value>> vec,
2066 size_t len, ComparatorMatchResult comp) {
2067 MOZ_ASSERT(vec.length() >= len);
2068
2069 Vector<NumericElement, 0, TempAllocPolicy> numElements(cx);
2070
2071 /* MergeSort uses the upper half as scratch space. */
2072 if (!numElements.resize(2 * len)) {
2073 return false;
2074 }
2075
2076 /* Convert Values to numerics. */
2077 for (size_t i = 0; i < len; i++) {
2078 if (!CheckForInterrupt(cx)) {
2079 return false;
2080 }
2081
2082 double dv;
2083 if (!ToNumber(cx, vec[i], &dv)) {
2084 return false;
2085 }
2086
2087 numElements[i] = {dv, i};
2088 }
2089
2090 /* Sort Values in vec numerically. */
2091 return MergeSortByKey(numElements.begin(), len, numElements.begin() + len,
2092 SortComparatorNumerics[comp], vec);
2093 }
2094
2095 static bool FillWithUndefined(JSContext* cx, HandleObject obj, uint32_t start,
2096 uint32_t count) {
2097 MOZ_ASSERT(start < start + count,
2098 "count > 0 and start + count doesn't overflow");
2099
2100 do {
2101 if (ObjectMayHaveExtraIndexedProperties(obj)) {
2102 break;
2103 }
2104
2105 NativeObject* nobj = &obj->as<NativeObject>();
2106 if (!nobj->isExtensible()) {
2107 break;
2108 }
2109
2110 if (obj->is<ArrayObject>() && !obj->as<ArrayObject>().lengthIsWritable() &&
2111 start + count >= obj->as<ArrayObject>().length()) {
2112 break;
2113 }
2114
2115 DenseElementResult result = nobj->ensureDenseElements(cx, start, count);
2116 if (result != DenseElementResult::Success) {
2117 if (result == DenseElementResult::Failure) {
2118 return false;
2119 }
2120 MOZ_ASSERT(result == DenseElementResult::Incomplete);
2121 break;
2122 }
2123
2124 if (obj->is<ArrayObject>() &&
2125 start + count >= obj->as<ArrayObject>().length()) {
2126 obj->as<ArrayObject>().setLengthToInitializedLength();
2127 }
2128
2129 for (uint32_t i = 0; i < count; i++) {
2130 nobj->setDenseElement(start + i, UndefinedHandleValue);
2131 }
2132
2133 return true;
2134 } while (false);
2135
2136 for (uint32_t i = 0; i < count; i++) {
2137 if (!CheckForInterrupt(cx) ||
2138 !SetArrayElement(cx, obj, start + i, UndefinedHandleValue)) {
2139 return false;
2140 }
2141 }
2142
2143 return true;
2144 }
2145
2146 static bool ArraySortWithoutComparator(JSContext* cx, Handle<JSObject*> obj,
2147 uint64_t length,
2148 ComparatorMatchResult comp) {
2149 MOZ_ASSERT(length > 1);
2150
2151 if (length > UINT32_MAX) {
2152 ReportAllocationOverflow(cx);
2153 return false;
2154 }
2155 uint32_t len = uint32_t(length);
2156
2157 /*
2158 * We need a temporary array of 2 * len Value to hold the array elements
2159 * and the scratch space for merge sort. Check that its size does not
2160 * overflow size_t, which would allow for indexing beyond the end of the
2161 * malloc'd vector.
2162 */
2163 #if JS_BITS_PER_WORD == 32
2164 if (size_t(len) > size_t(-1) / (2 * sizeof(Value))) {
2165 ReportAllocationOverflow(cx);
2166 return false;
2167 }
2168 #endif
2169
2170 size_t n, undefs;
2171 {
2172 Rooted<GCVector<Value>> vec(cx, GCVector<Value>(cx));
2173 if (!vec.reserve(2 * size_t(len))) {
2174 return false;
2175 }
2176
2177 /*
2178 * By ECMA 262, 15.4.4.11, a property that does not exist (which we
2179 * call a "hole") is always greater than an existing property with
2180 * value undefined and that is always greater than any other property.
2181 * Thus to sort holes and undefs we simply count them, sort the rest
2182 * of elements, append undefs after them and then make holes after
2183 * undefs.
2184 */
2185 undefs = 0;
2186 bool allStrings = true;
2187 bool allInts = true;
2188 RootedValue v(cx);
2189 if (IsPackedArray(obj)) {
2190 Handle<ArrayObject*> array = obj.as<ArrayObject>();
2191
2192 for (uint32_t i = 0; i < len; i++) {
2193 if (!CheckForInterrupt(cx)) {
2194 return false;
2195 }
2196
2197 v.set(array->getDenseElement(i));
2198 MOZ_ASSERT(!v.isMagic(JS_ELEMENTS_HOLE));
2199 if (v.isUndefined()) {
2200 ++undefs;
2201 continue;
2202 }
2203 vec.infallibleAppend(v);
2204 allStrings = allStrings && v.isString();
2205 allInts = allInts && v.isInt32();
2206 }
2207 } else {
2208 for (uint32_t i = 0; i < len; i++) {
2209 if (!CheckForInterrupt(cx)) {
2210 return false;
2211 }
2212
2213 bool hole;
2214 if (!HasAndGetElement(cx, obj, i, &hole, &v)) {
2215 return false;
2216 }
2217 if (hole) {
2218 continue;
2219 }
2220 if (v.isUndefined()) {
2221 ++undefs;
2222 continue;
2223 }
2224 vec.infallibleAppend(v);
2225 allStrings = allStrings && v.isString();
2226 allInts = allInts && v.isInt32();
2227 }
2228 }
2229
2230 /*
2231 * If the array only contains holes, we're done. But if it contains
2232 * undefs, those must be sorted to the front of the array.
2233 */
2234 n = vec.length();
2235 if (n == 0 && undefs == 0) {
2236 return true;
2237 }
2238
2239 /* Here len == n + undefs + number_of_holes. */
2240 if (comp == Match_None) {
2241 /*
2242 * Sort using the default comparator converting all elements to
2243 * strings.
2244 */
2245 if (allStrings) {
2246 MOZ_ALWAYS_TRUE(vec.resize(n * 2));
2247 if (!MergeSort(vec.begin(), n, vec.begin() + n,
2248 SortComparatorStrings(cx))) {
2249 return false;
2250 }
2251 } else if (allInts) {
2252 MOZ_ALWAYS_TRUE(vec.resize(n * 2));
2253 if (!MergeSort(vec.begin(), n, vec.begin() + n,
2254 SortComparatorLexicographicInt32())) {
2255 return false;
2256 }
2257 } else {
2258 if (!SortLexicographically(cx, &vec, n)) {
2259 return false;
2260 }
2261 }
2262 } else {
2263 if (allInts) {
2264 MOZ_ALWAYS_TRUE(vec.resize(n * 2));
2265 if (!MergeSort(vec.begin(), n, vec.begin() + n,
2266 SortComparatorInt32s[comp])) {
2267 return false;
2268 }
2269 } else {
2270 if (!SortNumerically(cx, &vec, n, comp)) {
2271 return false;
2272 }
2273 }
2274 }
2275
2276 if (!SetArrayElements(cx, obj, 0, uint32_t(n), vec.begin())) {
2277 return false;
2278 }
2279 }
2280
2281 /* Set undefs that sorted after the rest of elements. */
2282 if (undefs > 0) {
2283 if (!FillWithUndefined(cx, obj, n, undefs)) {
2284 return false;
2285 }
2286 n += undefs;
2287 }
2288
2289 /* Re-create any holes that sorted to the end of the array. */
2290 for (uint32_t i = n; i < len; i++) {
2291 if (!CheckForInterrupt(cx) || !DeletePropertyOrThrow(cx, obj, i)) {
2292 return false;
2293 }
2294 }
2295 return true;
2296 }
2297
2298 // This function handles sorting without a comparator function (or with a
2299 // trivial comparator function that we can pattern match) by calling
2300 // ArraySortWithoutComparator.
2301 //
2302 // If there's a non-trivial comparator function, it initializes the
2303 // ArraySortData struct for ArraySortData::sortArrayWithComparator. This
2304 // function must be called next to perform the sorting.
2305 //
2306 // This is separate from ArraySortData::sortArrayWithComparator because it lets
2307 // the compiler generate better code for ArraySortData::sortArrayWithComparator.
2308 //
2309 // https://tc39.es/ecma262/#sec-array.prototype.sort
2310 // 23.1.3.30 Array.prototype.sort ( comparefn )
2311 static MOZ_ALWAYS_INLINE bool ArraySortPrologue(JSContext* cx,
2312 Handle<Value> thisv,
2313 Handle<Value> comparefn,
2314 ArraySortData* d, bool* done) {
2315 // Step 1.
2316 if (MOZ_UNLIKELY(!comparefn.isUndefined() && !IsCallable(comparefn))) {
2317 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_SORT_ARG);
2318 return false;
2319 }
2320
2321 // Step 2.
2322 Rooted<JSObject*> obj(cx, ToObject(cx, thisv));
2323 if (!obj) {
2324 return false;
2325 }
2326
2327 // Step 3.
2328 uint64_t length;
2329 if (MOZ_UNLIKELY(!GetLengthPropertyInlined(cx, obj, &length))) {
2330 return false;
2331 }
2332
2333 // Arrays with less than two elements remain unchanged when sorted.
2334 if (length <= 1) {
2335 d->setReturnValue(obj);
2336 *done = true;
2337 return true;
2338 }
2339
2340 // Use a fast path if there's no comparator or if the comparator is a function
2341 // that we can pattern match.
2342 do {
2343 ComparatorMatchResult comp = Match_None;
2344 if (comparefn.isObject()) {
2345 comp = MatchNumericComparator(cx, &comparefn.toObject());
2346 if (comp == Match_Failure) {
2347 return false;
2348 }
2349 if (comp == Match_None) {
2350 // Pattern matching failed.
2351 break;
2352 }
2353 }
2354 if (!ArraySortWithoutComparator(cx, obj, length, comp)) {
2355 return false;
2356 }
2357 d->setReturnValue(obj);
2358 *done = true;
2359 return true;
2360 } while (false);
2361
2362 // Ensure length * 2 (used below) doesn't overflow UINT32_MAX.
2363 if (MOZ_UNLIKELY(length > UINT32_MAX / 2)) {
2364 ReportAllocationOverflow(cx);
2365 return false;
2366 }
2367 uint32_t len = uint32_t(length);
2368
2369 // Merge sort requires extra scratch space.
2370 bool needsScratchSpace = len > ArraySortData::InsertionSortMaxLength;
2371
2372 Rooted<ArraySortData::ValueVector> vec(cx);
2373 if (MOZ_UNLIKELY(!vec.reserve(needsScratchSpace ? (2 * len) : len))) {
2374 ReportOutOfMemory(cx);
2375 return false;
2376 }
2377
2378 // Append elements to the vector. Skip holes.
2379 if (IsPackedArray(obj)) {
2380 Handle<ArrayObject*> array = obj.as<ArrayObject>();
2381 const Value* elements = array->getDenseElements();
2382 vec.infallibleAppend(elements, len);
2383 } else {
2384 RootedValue v(cx);
2385 for (uint32_t i = 0; i < len; i++) {
2386 if (!CheckForInterrupt(cx)) {
2387 return false;
2388 }
2389
2390 bool hole;
2391 if (!HasAndGetElement(cx, obj, i, &hole, &v)) {
2392 return false;
2393 }
2394 if (hole) {
2395 continue;
2396 }
2397 vec.infallibleAppend(v);
2398 }
2399 // If there are only holes, the object is already sorted.
2400 if (vec.empty()) {
2401 d->setReturnValue(obj);
2402 *done = true;
2403 return true;
2404 }
2405 }
2406
2407 uint32_t denseLen = vec.length();
2408 if (needsScratchSpace) {
2409 MOZ_ALWAYS_TRUE(vec.resize(denseLen * 2));
2410 }
2411 d->init(obj, &comparefn.toObject(), std::move(vec.get()), len, denseLen);
2412
2413 // Continue in ArraySortData::sortArrayWithComparator.
2414 MOZ_ASSERT(!*done);
2415 return true;
2416 }
2417
2418 ArraySortResult js::CallComparatorSlow(ArraySortData* d, const Value& x,
2419 const Value& y) {
2420 JSContext* cx = d->cx();
2421 FixedInvokeArgs<2> callArgs(cx);
2422 callArgs[0].set(x);
2423 callArgs[1].set(y);
2424 Rooted<Value> comparefn(cx, ObjectValue(*d->comparator()));
2425 Rooted<Value> rval(cx);
2426 if (!js::Call(cx, comparefn, UndefinedHandleValue, callArgs, &rval)) {
2427 return ArraySortResult::Failure;
2428 }
2429 d->setComparatorReturnValue(rval);
2430 return ArraySortResult::Done;
2431 }
2432
2433 // static
2434 ArraySortResult ArraySortData::sortArrayWithComparator(ArraySortData* d) {
2435 ArraySortResult result = sortWithComparatorShared<ArraySortKind::Array>(d);
2436 if (result != ArraySortResult::Done) {
2437 return result;
2438 }
2439
2440 // Copy elements to the array.
2441 JSContext* cx = d->cx();
2442 Rooted<JSObject*> obj(cx, d->obj_);
2443 if (!SetArrayElements(cx, obj, 0, d->denseLen, d->list)) {
2444 return ArraySortResult::Failure;
2445 }
2446
2447 // Re-create any holes that sorted to the end of the array.
2448 for (uint32_t i = d->denseLen; i < d->length; i++) {
2449 if (!CheckForInterrupt(cx) || !DeletePropertyOrThrow(cx, obj, i)) {
2450 return ArraySortResult::Failure;
2451 }
2452 }
2453
2454 d->freeMallocData();
2455 d->setReturnValue(obj);
2456 return ArraySortResult::Done;
2457 }
2458
2459 // https://tc39.es/ecma262/#sec-array.prototype.sort
2460 // 23.1.3.30 Array.prototype.sort ( comparefn )
2461 bool js::array_sort(JSContext* cx, unsigned argc, Value* vp) {
2462 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "sort");
2463 CallArgs args = CallArgsFromVp(argc, vp);
2464
2465 // If we have a comparator argument, use the JIT trampoline implementation
2466 // instead. This avoids a performance cliff (especially with large arrays)
2467 // because C++ => JIT calls are much slower than Trampoline => JIT calls.
2468 if (args.hasDefined(0) && jit::IsBaselineInterpreterEnabled()) {
2469 return CallTrampolineNativeJitCode(cx, jit::TrampolineNative::ArraySort,
2470 args);
2471 }
2472
2473 Rooted<ArraySortData> data(cx, cx);
2474
2475 // On all return paths other than ArraySortData::sortArrayWithComparator
2476 // returning Done, we call freeMallocData to not fail debug assertions. This
2477 // matches the JIT trampoline where we can't rely on C++ destructors.
2478 auto freeData =
2479 mozilla::MakeScopeExit([&]() { data.get().freeMallocData(); });
2480
2481 bool done = false;
2482 if (!ArraySortPrologue(cx, args.thisv(), args.get(0), data.address(),
2483 &done)) {
2484 return false;
2485 }
2486 if (done) {
2487 args.rval().set(data.get().returnValue());
2488 return true;
2489 }
2490
2491 FixedInvokeArgs<2> callArgs(cx);
2492 Rooted<Value> rval(cx);
2493
2494 while (true) {
2495 ArraySortResult res =
2496 ArraySortData::sortArrayWithComparator(data.address());
2497 switch (res) {
2498 case ArraySortResult::Failure:
2499 return false;
2500
2501 case ArraySortResult::Done:
2502 freeData.release();
2503 args.rval().set(data.get().returnValue());
2504 return true;
2505
2506 case ArraySortResult::CallJS:
2507 case ArraySortResult::CallJSSameRealmNoRectifier:
2508 MOZ_ASSERT(data.get().comparatorThisValue().isUndefined());
2509 MOZ_ASSERT(&args[0].toObject() == data.get().comparator());
2510 callArgs[0].set(data.get().comparatorArg(0));
2511 callArgs[1].set(data.get().comparatorArg(1));
2512 if (!js::Call(cx, args[0], UndefinedHandleValue, callArgs, &rval)) {
2513 return false;
2514 }
2515 data.get().setComparatorReturnValue(rval);
2516 break;
2517 }
2518 }
2519 }
2520
2521 ArraySortResult js::ArraySortFromJit(JSContext* cx,
2522 jit::TrampolineNativeFrameLayout* frame) {
2523 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "sort");
2524 // Initialize the ArraySortData class stored in the trampoline frame.
2525 void* dataUninit = frame->getFrameData<ArraySortData>();
2526 auto* data = new (dataUninit) ArraySortData(cx);
2527
2528 Rooted<Value> thisv(cx, frame->thisv());
2529 Rooted<Value> comparefn(cx);
2530 if (frame->numActualArgs() > 0) {
2531 comparefn = frame->actualArgs()[0];
2532 }
2533
2534 bool done = false;
2535 if (!ArraySortPrologue(cx, thisv, comparefn, data, &done)) {
2536 return ArraySortResult::Failure;
2537 }
2538 if (done) {
2539 data->freeMallocData();
2540 return ArraySortResult::Done;
2541 }
2542
2543 return ArraySortData::sortArrayWithComparator(data);
2544 }
2545
2546 void ArraySortData::trace(JSTracer* trc) {
2547 TraceNullableRoot(trc, &comparator_, "comparator_");
2548 TraceRoot(trc, &thisv, "thisv");
2549 TraceRoot(trc, &callArgs[0], "callArgs0");
2550 TraceRoot(trc, &callArgs[1], "callArgs1");
2551 vec.trace(trc);
2552 TraceRoot(trc, &item, "item");
2553 TraceNullableRoot(trc, &obj_, "obj");
2554 }
2555
2556 bool js::NewbornArrayPush(JSContext* cx, HandleObject obj, const Value& v) {
2557 Handle<ArrayObject*> arr = obj.as<ArrayObject>();
2558
2559 MOZ_ASSERT(!v.isMagic());
2560 MOZ_ASSERT(arr->lengthIsWritable());
2561
2562 uint32_t length = arr->length();
2563 MOZ_ASSERT(length <= arr->getDenseCapacity());
2564
2565 if (!arr->ensureElements(cx, length + 1)) {
2566 return false;
2567 }
2568
2569 arr->setDenseInitializedLength(length + 1);
2570 arr->setLengthToInitializedLength();
2571 arr->initDenseElement(length, v);
2572 return true;
2573 }
2574
2575 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
2576 // 22.1.3.18 Array.prototype.push ( ...items )
2577 static bool array_push(JSContext* cx, unsigned argc, Value* vp) {
2578 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "push");
2579 CallArgs args = CallArgsFromVp(argc, vp);
2580
2581 // Step 1.
2582 RootedObject obj(cx, ToObject(cx, args.thisv()));
2583 if (!obj) {
2584 return false;
2585 }
2586
2587 // Step 2.
2588 uint64_t length;
2589 if (!GetLengthPropertyInlined(cx, obj, &length)) {
2590 return false;
2591 }
2592
2593 if (!ObjectMayHaveExtraIndexedProperties(obj) && length <= UINT32_MAX) {
2594 DenseElementResult result =
2595 obj->as<NativeObject>().setOrExtendDenseElements(
2596 cx, uint32_t(length), args.array(), args.length());
2597 if (result != DenseElementResult::Incomplete) {
2598 if (result == DenseElementResult::Failure) {
2599 return false;
2600 }
2601
2602 uint32_t newlength = uint32_t(length) + args.length();
2603 args.rval().setNumber(newlength);
2604
2605 // setOrExtendDenseElements takes care of updating the length for
2606 // arrays. Handle updates to the length of non-arrays here.
2607 if (!obj->is<ArrayObject>()) {
2608 MOZ_ASSERT(obj->is<NativeObject>());
2609 return SetLengthProperty(cx, obj, newlength);
2610 }
2611
2612 return true;
2613 }
2614 }
2615
2616 // Step 5.
2617 uint64_t newlength = length + args.length();
2618 if (newlength >= uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) {
2619 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2620 JSMSG_TOO_LONG_ARRAY);
2621 return false;
2622 }
2623
2624 // Steps 3-6.
2625 if (!SetArrayElements(cx, obj, length, args.length(), args.array())) {
2626 return false;
2627 }
2628
2629 // Steps 7-8.
2630 args.rval().setNumber(double(newlength));
2631 return SetLengthProperty(cx, obj, newlength);
2632 }
2633
2634 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
2635 // 22.1.3.17 Array.prototype.pop ( )
2636 bool js::array_pop(JSContext* cx, unsigned argc, Value* vp) {
2637 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "pop");
2638 CallArgs args = CallArgsFromVp(argc, vp);
2639
2640 // Step 1.
2641 RootedObject obj(cx, ToObject(cx, args.thisv()));
2642 if (!obj) {
2643 return false;
2644 }
2645
2646 // Step 2.
2647 uint64_t index;
2648 if (!GetLengthPropertyInlined(cx, obj, &index)) {
2649 return false;
2650 }
2651
2652 // Steps 3-4.
2653 if (index == 0) {
2654 // Step 3.b.
2655 args.rval().setUndefined();
2656 } else {
2657 // Steps 4.a-b.
2658 index--;
2659
2660 // Steps 4.c, 4.f.
2661 if (!GetArrayElement(cx, obj, index, args.rval())) {
2662 return false;
2663 }
2664
2665 // Steps 4.d.
2666 if (!DeletePropertyOrThrow(cx, obj, index)) {
2667 return false;
2668 }
2669 }
2670
2671 // Steps 3.a, 4.e.
2672 return SetLengthProperty(cx, obj, index);
2673 }
2674
2675 void js::ArrayShiftMoveElements(ArrayObject* arr) {
2676 AutoUnsafeCallWithABI unsafe;
2677 MOZ_ASSERT(arr->isExtensible());
2678 MOZ_ASSERT(arr->lengthIsWritable());
2679 MOZ_ASSERT(IsPackedArray(arr));
2680 MOZ_ASSERT(!arr->denseElementsHaveMaybeInIterationFlag());
2681
2682 size_t initlen = arr->getDenseInitializedLength();
2683 MOZ_ASSERT(initlen > 0);
2684
2685 if (!arr->tryShiftDenseElements(1)) {
2686 arr->moveDenseElements(0, 1, initlen - 1);
2687 arr->setDenseInitializedLength(initlen - 1);
2688 }
2689
2690 MOZ_ASSERT(arr->getDenseInitializedLength() == initlen - 1);
2691 arr->setLengthToInitializedLength();
2692 }
2693
2694 static inline void SetInitializedLength(JSContext* cx, NativeObject* obj,
2695 size_t initlen) {
2696 MOZ_ASSERT(obj->isExtensible());
2697
2698 size_t oldInitlen = obj->getDenseInitializedLength();
2699 obj->setDenseInitializedLength(initlen);
2700 if (initlen < oldInitlen) {
2701 obj->shrinkElements(cx, initlen);
2702 }
2703 }
2704
2705 static DenseElementResult ArrayShiftDenseKernel(JSContext* cx, HandleObject obj,
2706 MutableHandleValue rval) {
2707 if (!IsPackedArray(obj) && ObjectMayHaveExtraIndexedProperties(obj)) {
2708 return DenseElementResult::Incomplete;
2709 }
2710
2711 Handle<NativeObject*> nobj = obj.as<NativeObject>();
2712 if (nobj->denseElementsMaybeInIteration()) {
2713 return DenseElementResult::Incomplete;
2714 }
2715
2716 if (!nobj->isExtensible()) {
2717 return DenseElementResult::Incomplete;
2718 }
2719
2720 size_t initlen = nobj->getDenseInitializedLength();
2721 if (initlen == 0) {
2722 return DenseElementResult::Incomplete;
2723 }
2724
2725 rval.set(nobj->getDenseElement(0));
2726 if (rval.isMagic(JS_ELEMENTS_HOLE)) {
2727 rval.setUndefined();
2728 }
2729
2730 if (nobj->tryShiftDenseElements(1)) {
2731 return DenseElementResult::Success;
2732 }
2733
2734 nobj->moveDenseElements(0, 1, initlen - 1);
2735
2736 SetInitializedLength(cx, nobj, initlen - 1);
2737 return DenseElementResult::Success;
2738 }
2739
2740 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
2741 // 22.1.3.22 Array.prototype.shift ( )
2742 static bool array_shift(JSContext* cx, unsigned argc, Value* vp) {
2743 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "shift");
2744 CallArgs args = CallArgsFromVp(argc, vp);
2745
2746 // Step 1.
2747 RootedObject obj(cx, ToObject(cx, args.thisv()));
2748 if (!obj) {
2749 return false;
2750 }
2751
2752 // Step 2.
2753 uint64_t len;
2754 if (!GetLengthPropertyInlined(cx, obj, &len)) {
2755 return false;
2756 }
2757
2758 // Step 3.
2759 if (len == 0) {
2760 // Step 3.a.
2761 if (!SetLengthProperty(cx, obj, uint32_t(0))) {
2762 return false;
2763 }
2764
2765 // Step 3.b.
2766 args.rval().setUndefined();
2767 return true;
2768 }
2769
2770 uint64_t newlen = len - 1;
2771
2772 /* Fast paths. */
2773 uint64_t startIndex;
2774 DenseElementResult result = ArrayShiftDenseKernel(cx, obj, args.rval());
2775 if (result != DenseElementResult::Incomplete) {
2776 if (result == DenseElementResult::Failure) {
2777 return false;
2778 }
2779
2780 if (len <= UINT32_MAX) {
2781 return SetLengthProperty(cx, obj, newlen);
2782 }
2783
2784 startIndex = UINT32_MAX - 1;
2785 } else {
2786 // Steps 4, 9.
2787 if (!GetElement(cx, obj, 0, args.rval())) {
2788 return false;
2789 }
2790
2791 startIndex = 0;
2792 }
2793
2794 // Steps 5-6.
2795 RootedValue value(cx);
2796 for (uint64_t i = startIndex; i < newlen; i++) {
2797 if (!CheckForInterrupt(cx)) {
2798 return false;
2799 }
2800 bool hole;
2801 if (!HasAndGetElement(cx, obj, i + 1, &hole, &value)) {
2802 return false;
2803 }
2804 if (hole) {
2805 if (!DeletePropertyOrThrow(cx, obj, i)) {
2806 return false;
2807 }
2808 } else {
2809 if (!SetArrayElement(cx, obj, i, value)) {
2810 return false;
2811 }
2812 }
2813 }
2814
2815 // Step 7.
2816 if (!DeletePropertyOrThrow(cx, obj, newlen)) {
2817 return false;
2818 }
2819
2820 // Step 8.
2821 return SetLengthProperty(cx, obj, newlen);
2822 }
2823
2824 // ES2017 draft rev 1b0184bc17fc09a8ddcf4aeec9b6d9fcac4eafce
2825 // 22.1.3.29 Array.prototype.unshift ( ...items )
2826 static bool array_unshift(JSContext* cx, unsigned argc, Value* vp) {
2827 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "unshift");
2828 CallArgs args = CallArgsFromVp(argc, vp);
2829
2830 // Step 1.
2831 RootedObject obj(cx, ToObject(cx, args.thisv()));
2832 if (!obj) {
2833 return false;
2834 }
2835
2836 // Step 2.
2837 uint64_t length;
2838 if (!GetLengthPropertyInlined(cx, obj, &length)) {
2839 return false;
2840 }
2841
2842 // Steps 3-4.
2843 if (args.length() > 0) {
2844 bool optimized = false;
2845 do {
2846 if (length > UINT32_MAX) {
2847 break;
2848 }
2849 if (ObjectMayHaveExtraIndexedProperties(obj)) {
2850 break;
2851 }
2852 NativeObject* nobj = &obj->as<NativeObject>();
2853 if (nobj->denseElementsMaybeInIteration()) {
2854 break;
2855 }
2856 if (!nobj->isExtensible()) {
2857 break;
2858 }
2859 if (nobj->is<ArrayObject>() &&
2860 !nobj->as<ArrayObject>().lengthIsWritable()) {
2861 break;
2862 }
2863 if (!nobj->tryUnshiftDenseElements(args.length())) {
2864 DenseElementResult result =
2865 nobj->ensureDenseElements(cx, uint32_t(length), args.length());
2866 if (result != DenseElementResult::Success) {
2867 if (result == DenseElementResult::Failure) {
2868 return false;
2869 }
2870 MOZ_ASSERT(result == DenseElementResult::Incomplete);
2871 break;
2872 }
2873 if (length > 0) {
2874 nobj->moveDenseElements(args.length(), 0, uint32_t(length));
2875 }
2876 }
2877 for (uint32_t i = 0; i < args.length(); i++) {
2878 nobj->setDenseElement(i, args[i]);
2879 }
2880 optimized = true;
2881 } while (false);
2882
2883 if (!optimized) {
2884 if (length > 0) {
2885 uint64_t last = length;
2886 uint64_t upperIndex = last + args.length();
2887
2888 // Step 4.a.
2889 if (upperIndex >= uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) {
2890 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2891 JSMSG_TOO_LONG_ARRAY);
2892 return false;
2893 }
2894
2895 // Steps 4.b-c.
2896 RootedValue value(cx);
2897 do {
2898 --last;
2899 --upperIndex;
2900 if (!CheckForInterrupt(cx)) {
2901 return false;
2902 }
2903 bool hole;
2904 if (!HasAndGetElement(cx, obj, last, &hole, &value)) {
2905 return false;
2906 }
2907 if (hole) {
2908 if (!DeletePropertyOrThrow(cx, obj, upperIndex)) {
2909 return false;
2910 }
2911 } else {
2912 if (!SetArrayElement(cx, obj, upperIndex, value)) {
2913 return false;
2914 }
2915 }
2916 } while (last != 0);
2917 }
2918
2919 // Steps 4.d-f.
2920 /* Copy from args to the bottom of the array. */
2921 if (!SetArrayElements(cx, obj, 0, args.length(), args.array())) {
2922 return false;
2923 }
2924 }
2925 }
2926
2927 // Step 5.
2928 uint64_t newlength = length + args.length();
2929 if (!SetLengthProperty(cx, obj, newlength)) {
2930 return false;
2931 }
2932
2933 // Step 6.
2934 /* Follow Perl by returning the new array length. */
2935 args.rval().setNumber(double(newlength));
2936 return true;
2937 }
2938
2939 enum class ArrayAccess { Read, Write };
2940
2941 /*
2942 * Returns true if this is a dense array whose properties ending at |endIndex|
2943 * (exclusive) may be accessed (get, set, delete) directly through its
2944 * contiguous vector of elements without fear of getters, setters, etc. along
2945 * the prototype chain, or of enumerators requiring notification of
2946 * modifications.
2947 */
2948 template <ArrayAccess Access>
2949 static bool CanOptimizeForDenseStorage(HandleObject arr, uint64_t endIndex) {
2950 /* If the desired properties overflow dense storage, we can't optimize. */
2951 if (endIndex > UINT32_MAX) {
2952 return false;
2953 }
2954
2955 if (Access == ArrayAccess::Read) {
2956 /*
2957 * Dense storage read access is possible for any packed array as long
2958 * as we only access properties within the initialized length. In all
2959 * other cases we need to ensure there are no other indexed properties
2960 * on this object or on the prototype chain. Callers are required to
2961 * clamp the read length, so it doesn't exceed the initialized length.
2962 */
2963 if (IsPackedArray(arr) &&
2964 endIndex <= arr->as<ArrayObject>().getDenseInitializedLength()) {
2965 return true;
2966 }
2967 return !ObjectMayHaveExtraIndexedProperties(arr);
2968 }
2969
2970 /* There's no optimizing possible if it's not an array. */
2971 if (!arr->is<ArrayObject>()) {
2972 return false;
2973 }
2974
2975 /* If the length is non-writable, always pick the slow path */
2976 if (!arr->as<ArrayObject>().lengthIsWritable()) {
2977 return false;
2978 }
2979
2980 /* Also pick the slow path if the object is non-extensible. */
2981 if (!arr->as<ArrayObject>().isExtensible()) {
2982 return false;
2983 }
2984
2985 /* Also pick the slow path if the object is being iterated over. */
2986 if (arr->as<ArrayObject>().denseElementsMaybeInIteration()) {
2987 return false;
2988 }
2989
2990 /* Or we attempt to write to indices outside the initialized length. */
2991 if (endIndex > arr->as<ArrayObject>().getDenseInitializedLength()) {
2992 return false;
2993 }
2994
2995 /*
2996 * Now watch out for getters and setters along the prototype chain or in
2997 * other indexed properties on the object. Packed arrays don't have any
2998 * other indexed properties by definition.
2999 */
3000 return IsPackedArray(arr) || !ObjectMayHaveExtraIndexedProperties(arr);
3001 }
3002
3003 static ArrayObject* CopyDenseArrayElements(JSContext* cx,
3004 Handle<NativeObject*> obj,
3005 uint32_t begin, uint32_t count) {
3006 size_t initlen = obj->getDenseInitializedLength();
3007 MOZ_ASSERT(initlen <= UINT32_MAX,
3008 "initialized length shouldn't exceed UINT32_MAX");
3009 uint32_t newlength = 0;
3010 if (initlen > begin) {
3011 newlength = std::min<uint32_t>(initlen - begin, count);
3012 }
3013
3014 ArrayObject* narr = NewDenseFullyAllocatedArray(cx, newlength);
3015 if (!narr) {
3016 return nullptr;
3017 }
3018
3019 MOZ_ASSERT(count >= narr->length());
3020 narr->setLength(cx, count);
3021
3022 if (newlength > 0) {
3023 narr->initDenseElements(obj, begin, newlength);
3024 }
3025
3026 return narr;
3027 }
3028
3029 static bool CopyArrayElements(JSContext* cx, HandleObject obj, uint64_t begin,
3030 uint64_t count, Handle<ArrayObject*> result) {
3031 MOZ_ASSERT(result->length() == count);
3032
3033 uint64_t startIndex = 0;
3034 RootedValue value(cx);
3035
3036 // Use dense storage for new indexed properties where possible.
3037 {
3038 uint32_t index = 0;
3039 uint32_t limit = std::min<uint32_t>(count, PropertyKey::IntMax);
3040 for (; index < limit; index++) {
3041 bool hole;
3042 if (!CheckForInterrupt(cx) ||
3043 !HasAndGetElement(cx, obj, begin + index, &hole, &value)) {
3044 return false;
3045 }
3046
3047 if (!hole) {
3048 DenseElementResult edResult = result->ensureDenseElements(cx, index, 1);
3049 if (edResult != DenseElementResult::Success) {
3050 if (edResult == DenseElementResult::Failure) {
3051 return false;
3052 }
3053
3054 MOZ_ASSERT(edResult == DenseElementResult::Incomplete);
3055 if (!DefineDataElement(cx, result, index, value)) {
3056 return false;
3057 }
3058
3059 break;
3060 }
3061 result->setDenseElement(index, value);
3062 }
3063 }
3064 startIndex = index + 1;
3065 }
3066
3067 // Copy any remaining elements.
3068 for (uint64_t i = startIndex; i < count; i++) {
3069 bool hole;
3070 if (!CheckForInterrupt(cx) ||
3071 !HasAndGetElement(cx, obj, begin + i, &hole, &value)) {
3072 return false;
3073 }
3074
3075 if (!hole && !DefineArrayElement(cx, result, i, value)) {
3076 return false;
3077 }
3078 }
3079 return true;
3080 }
3081
3082 // Helpers for array_splice_impl() and array_to_spliced()
3083 //
3084 // Initialize variables common to splice() and toSpliced():
3085 // - GetItemCount() returns the number of new elements being added.
3086 // - GetActualDeleteCount() returns the number of elements being deleted.
3087
3088 static uint32_t GetItemCount(const CallArgs& args) {
3089 if (args.length() < 2) {
3090 return 0;
3091 }
3092 return (args.length() - 2);
3093 }
3094
3095 static bool GetActualDeleteCount(JSContext* cx, const CallArgs& args,
3096 HandleObject obj, uint64_t len,
3097 uint64_t actualStart, uint32_t insertCount,
3098 uint64_t* actualDeleteCount) {
3099 MOZ_ASSERT(len < DOUBLE_INTEGRAL_PRECISION_LIMIT);
3100 MOZ_ASSERT(actualStart <= len);
3101 MOZ_ASSERT(insertCount == GetItemCount(args));
3102
3103 if (args.length() < 1) {
3104 // Step 8. If start is not present, then let actualDeleteCount be 0.
3105 *actualDeleteCount = 0;
3106 } else if (args.length() < 2) {
3107 // Step 9. Else if deleteCount is not present, then let actualDeleteCount be
3108 // len - actualStart.
3109 *actualDeleteCount = len - actualStart;
3110 } else {
3111 // Step 10.a. Else, let dc be toIntegerOrInfinity(deleteCount).
3112 double deleteCount;
3113 if (!ToInteger(cx, args.get(1), &deleteCount)) {
3114 return false;
3115 }
3116
3117 // Step 10.b. Let actualDeleteCount be the result of clamping dc between 0
3118 // and len - actualStart.
3119 *actualDeleteCount =
3120 uint64_t(std::clamp(deleteCount, 0.0, double(len - actualStart)));
3121 MOZ_ASSERT(*actualDeleteCount <= len);
3122
3123 // Step 11. Let newLen be len + insertCount - actualDeleteCount.
3124 // Step 12. If newLen > 2^53 - 1, throw a TypeError exception.
3125 if (len + uint64_t(insertCount) - *actualDeleteCount >=
3126 uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT)) {
3127 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3128 JSMSG_TOO_LONG_ARRAY);
3129 return false;
3130 }
3131 }
3132 MOZ_ASSERT(actualStart + *actualDeleteCount <= len);
3133
3134 return true;
3135 }
3136
3137 static bool array_splice_impl(JSContext* cx, unsigned argc, Value* vp,
3138 bool returnValueIsUsed) {
3139 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "splice");
3140 CallArgs args = CallArgsFromVp(argc, vp);
3141
3142 /* Step 1. */
3143 RootedObject obj(cx, ToObject(cx, args.thisv()));
3144 if (!obj) {
3145 return false;
3146 }
3147
3148 /* Step 2. */
3149 uint64_t len;
3150 if (!GetLengthPropertyInlined(cx, obj, &len)) {
3151 return false;
3152 }
3153
3154 /* Steps 3-6. */
3155 /* actualStart is the index after which elements will be
3156 deleted and/or new elements will be added */
3157 uint64_t actualStart = 0;
3158 if (args.hasDefined(0)) {
3159 if (!ToIntegerIndex(cx, args[0], len, &actualStart)) {
3160 return false;
3161 }
3162 }
3163 MOZ_ASSERT(actualStart <= len);
3164
3165 /* Steps 7-10.*/
3166 /* itemCount is the number of elements being added */
3167 uint32_t itemCount = GetItemCount(args);
3168
3169 /* actualDeleteCount is the number of elements being deleted */
3170 uint64_t actualDeleteCount;
3171 if (!GetActualDeleteCount(cx, args, obj, len, actualStart, itemCount,
3172 &actualDeleteCount)) {
3173 return false;
3174 }
3175
3176 RootedObject arr(cx);
3177 if (IsArraySpecies(cx, obj)) {
3178 if (actualDeleteCount > UINT32_MAX) {
3179 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3180 JSMSG_BAD_ARRAY_LENGTH);
3181 return false;
3182 }
3183 uint32_t count = uint32_t(actualDeleteCount);
3184
3185 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj,
3186 actualStart + count)) {
3187 MOZ_ASSERT(actualStart <= UINT32_MAX,
3188 "if actualStart + count <= UINT32_MAX, then actualStart <= "
3189 "UINT32_MAX");
3190 if (returnValueIsUsed) {
3191 /* Steps 11-13. */
3192 arr = CopyDenseArrayElements(cx, obj.as<NativeObject>(),
3193 uint32_t(actualStart), count);
3194 if (!arr) {
3195 return false;
3196 }
3197 }
3198 } else {
3199 /* Step 11. */
3200 arr = NewDenseFullyAllocatedArray(cx, count);
3201 if (!arr) {
3202 return false;
3203 }
3204
3205 /* Steps 12-13. */
3206 if (!CopyArrayElements(cx, obj, actualStart, count,
3207 arr.as<ArrayObject>())) {
3208 return false;
3209 }
3210 }
3211 } else {
3212 /* Step 11. */
3213 if (!ArraySpeciesCreate(cx, obj, actualDeleteCount, &arr)) {
3214 return false;
3215 }
3216
3217 /* Steps 12-13. */
3218 RootedValue fromValue(cx);
3219 for (uint64_t k = 0; k < actualDeleteCount; k++) {
3220 if (!CheckForInterrupt(cx)) {
3221 return false;
3222 }
3223
3224 /* Steps 13.b, 13.c.i. */
3225 bool hole;
3226 if (!HasAndGetElement(cx, obj, actualStart + k, &hole, &fromValue)) {
3227 return false;
3228 }
3229
3230 /* Step 13.c. */
3231 if (!hole) {
3232 /* Step 13.c.ii. */
3233 if (!DefineArrayElement(cx, arr, k, fromValue)) {
3234 return false;
3235 }
3236 }
3237 }
3238
3239 /* Step 14. */
3240 if (!SetLengthProperty(cx, arr, actualDeleteCount)) {
3241 return false;
3242 }
3243 }
3244
3245 /* Step 15. */
3246 uint64_t finalLength = len - actualDeleteCount + itemCount;
3247
3248 if (itemCount < actualDeleteCount) {
3249 /* Step 16: the array is being shrunk. */
3250 uint64_t sourceIndex = actualStart + actualDeleteCount;
3251 uint64_t targetIndex = actualStart + itemCount;
3252
3253 if (CanOptimizeForDenseStorage<ArrayAccess::Write>(obj, len)) {
3254 MOZ_ASSERT(sourceIndex <= len && targetIndex <= len && len <= UINT32_MAX,
3255 "sourceIndex and targetIndex are uint32 array indices");
3256 MOZ_ASSERT(finalLength < len, "finalLength is strictly less than len");
3257 MOZ_ASSERT(obj->is<NativeObject>());
3258
3259 /* Step 16.b. */
3260 Handle<ArrayObject*> arr = obj.as<ArrayObject>();
3261 if (targetIndex != 0 || !arr->tryShiftDenseElements(sourceIndex)) {
3262 arr->moveDenseElements(uint32_t(targetIndex), uint32_t(sourceIndex),
3263 uint32_t(len - sourceIndex));
3264 }
3265
3266 /* Steps 20. */
3267 SetInitializedLength(cx, arr, finalLength);
3268 } else {
3269 /*
3270 * This is all very slow if the length is very large. We don't yet
3271 * have the ability to iterate in sorted order, so we just do the
3272 * pessimistic thing and let CheckForInterrupt handle the
3273 * fallout.
3274 */
3275
3276 /* Step 16. */
3277 RootedValue fromValue(cx);
3278 for (uint64_t from = sourceIndex, to = targetIndex; from < len;
3279 from++, to++) {
3280 /* Steps 15.b.i-ii (implicit). */
3281
3282 if (!CheckForInterrupt(cx)) {
3283 return false;
3284 }
3285
3286 /* Steps 16.b.iii-v */
3287 bool hole;
3288 if (!HasAndGetElement(cx, obj, from, &hole, &fromValue)) {
3289 return false;
3290 }
3291
3292 if (hole) {
3293 if (!DeletePropertyOrThrow(cx, obj, to)) {
3294 return false;
3295 }
3296 } else {
3297 if (!SetArrayElement(cx, obj, to, fromValue)) {
3298 return false;
3299 }
3300 }
3301 }
3302
3303 /* Step 16d. */
3304 if (!DeletePropertiesOrThrow(cx, obj, len, finalLength)) {
3305 return false;
3306 }
3307 }
3308 } else if (itemCount > actualDeleteCount) {
3309 MOZ_ASSERT(actualDeleteCount <= UINT32_MAX);
3310 uint32_t deleteCount = uint32_t(actualDeleteCount);
3311
3312 /* Step 17. */
3313
3314 // Fast path for when we can simply extend and move the dense elements.
3315 auto extendElements = [len, itemCount, deleteCount](JSContext* cx,
3316 HandleObject obj) {
3317 if (!obj->is<ArrayObject>()) {
3318 return DenseElementResult::Incomplete;
3319 }
3320 if (len > UINT32_MAX) {
3321 return DenseElementResult::Incomplete;
3322 }
3323
3324 // Ensure there are no getters/setters or other extra indexed properties.
3325 if (ObjectMayHaveExtraIndexedProperties(obj)) {
3326 return DenseElementResult::Incomplete;
3327 }
3328
3329 // Watch out for arrays with non-writable length or non-extensible arrays.
3330 // In these cases `splice` may have to throw an exception so we let the
3331 // slow path handle it. We also have to ensure we maintain the
3332 // |capacity <= initializedLength| invariant for such objects. See
3333 // NativeObject::shrinkCapacityToInitializedLength.
3334 Handle<ArrayObject*> arr = obj.as<ArrayObject>();
3335 if (!arr->lengthIsWritable() || !arr->isExtensible()) {
3336 return DenseElementResult::Incomplete;
3337 }
3338
3339 // Also use the slow path if there might be an active for-in iterator so
3340 // that we don't have to worry about suppressing deleted properties.
3341 if (arr->denseElementsMaybeInIteration()) {
3342 return DenseElementResult::Incomplete;
3343 }
3344
3345 return arr->ensureDenseElements(cx, uint32_t(len),
3346 itemCount - deleteCount);
3347 };
3348
3349 DenseElementResult res = extendElements(cx, obj);
3350 if (res == DenseElementResult::Failure) {
3351 return false;
3352 }
3353 if (res == DenseElementResult::Success) {
3354 MOZ_ASSERT(finalLength <= UINT32_MAX);
3355 MOZ_ASSERT((actualStart + actualDeleteCount) <= len && len <= UINT32_MAX,
3356 "start and deleteCount are uint32 array indices");
3357 MOZ_ASSERT(actualStart + itemCount <= UINT32_MAX,
3358 "can't overflow because |len - actualDeleteCount + itemCount "
3359 "<= UINT32_MAX| "
3360 "and |actualStart <= len - actualDeleteCount| are both true");
3361 uint32_t start = uint32_t(actualStart);
3362 uint32_t length = uint32_t(len);
3363
3364 Handle<ArrayObject*> arr = obj.as<ArrayObject>();
3365 arr->moveDenseElements(start + itemCount, start + deleteCount,
3366 length - (start + deleteCount));
3367
3368 /* Step 20. */
3369 SetInitializedLength(cx, arr, finalLength);
3370 } else {
3371 MOZ_ASSERT(res == DenseElementResult::Incomplete);
3372
3373 RootedValue fromValue(cx);
3374 for (uint64_t k = len - actualDeleteCount; k > actualStart; k--) {
3375 if (!CheckForInterrupt(cx)) {
3376 return false;
3377 }
3378
3379 /* Step 17.b.i. */
3380 uint64_t from = k + actualDeleteCount - 1;
3381
3382 /* Step 17.b.ii. */
3383 uint64_t to = k + itemCount - 1;
3384
3385 /* Steps 17.b.iii, 17.b.iv.1. */
3386 bool hole;
3387 if (!HasAndGetElement(cx, obj, from, &hole, &fromValue)) {
3388 return false;
3389 }
3390
3391 /* Steps 17.b.iv. */
3392 if (hole) {
3393 /* Step 17.b.v.1. */
3394 if (!DeletePropertyOrThrow(cx, obj, to)) {
3395 return false;
3396 }
3397 } else {
3398 /* Step 17.b.iv.2. */
3399 if (!SetArrayElement(cx, obj, to, fromValue)) {
3400 return false;
3401 }
3402 }
3403 }
3404 }
3405 }
3406
3407 Value* items = args.array() + 2;
3408
3409 /* Steps 18-19. */
3410 if (!SetArrayElements(cx, obj, actualStart, itemCount, items)) {
3411 return false;
3412 }
3413
3414 /* Step 20. */
3415 if (!SetLengthProperty(cx, obj, finalLength)) {
3416 return false;
3417 }
3418
3419 /* Step 21. */
3420 if (returnValueIsUsed) {
3421 args.rval().setObject(*arr);
3422 }
3423
3424 return true;
3425 }
3426
3427 /* ES 2016 draft Mar 25, 2016 22.1.3.26. */
3428 static bool array_splice(JSContext* cx, unsigned argc, Value* vp) {
3429 return array_splice_impl(cx, argc, vp, true);
3430 }
3431
3432 static bool array_splice_noRetVal(JSContext* cx, unsigned argc, Value* vp) {
3433 return array_splice_impl(cx, argc, vp, false);
3434 }
3435
3436 static void CopyDenseElementsFillHoles(ArrayObject* arr, NativeObject* nobj,
3437 uint32_t length) {
3438 // Ensure |arr| is an empty array with sufficient capacity.
3439 MOZ_ASSERT(arr->getDenseInitializedLength() == 0);
3440 MOZ_ASSERT(arr->getDenseCapacity() >= length);
3441 MOZ_ASSERT(length > 0);
3442
3443 uint32_t count = std::min(nobj->getDenseInitializedLength(), length);
3444
3445 if (count > 0) {
3446 if (nobj->denseElementsArePacked()) {
3447 // Copy all dense elements when no holes are present.
3448 arr->initDenseElements(nobj, 0, count);
3449 } else {
3450 arr->setDenseInitializedLength(count);
3451
3452 // Handle each element separately to filter out holes.
3453 for (uint32_t i = 0; i < count; i++) {
3454 Value val = nobj->getDenseElement(i);
3455 if (val.isMagic(JS_ELEMENTS_HOLE)) {
3456 val = UndefinedValue();
3457 }
3458 arr->initDenseElement(i, val);
3459 }
3460 }
3461 }
3462
3463 // Fill trailing holes with undefined.
3464 if (count < length) {
3465 arr->setDenseInitializedLength(length);
3466
3467 for (uint32_t i = count; i < length; i++) {
3468 arr->initDenseElement(i, UndefinedValue());
3469 }
3470 }
3471
3472 // Ensure |length| elements have been copied and no holes are present.
3473 MOZ_ASSERT(arr->getDenseInitializedLength() == length);
3474 MOZ_ASSERT(arr->denseElementsArePacked());
3475 }
3476
3477 // ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b
3478 // 23.1.3.35 Array.prototype.toSpliced ( start, skipCount, ...items )
3479 static bool array_toSpliced(JSContext* cx, unsigned argc, Value* vp) {
3480 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "toSpliced");
3481 CallArgs args = CallArgsFromVp(argc, vp);
3482
3483 // Step 1. Let O be ? ToObject(this value).
3484 RootedObject obj(cx, ToObject(cx, args.thisv()));
3485 if (!obj) {
3486 return false;
3487 }
3488
3489 // Step 2. Let len be ? LengthOfArrayLike(O).
3490 uint64_t len;
3491 if (!GetLengthPropertyInlined(cx, obj, &len)) {
3492 return false;
3493 }
3494
3495 // Steps 3-6.
3496 // |actualStart| is the index after which elements will be deleted and/or
3497 // new elements will be added
3498 uint64_t actualStart = 0;
3499 if (args.hasDefined(0)) {
3500 if (!ToIntegerIndex(cx, args[0], len, &actualStart)) {
3501 return false;
3502 }
3503 }
3504 MOZ_ASSERT(actualStart <= len);
3505
3506 // Step 7. Let insertCount be the number of elements in items.
3507 uint32_t insertCount = GetItemCount(args);
3508
3509 // Steps 8-10.
3510 // actualDeleteCount is the number of elements being deleted
3511 uint64_t actualDeleteCount;
3512 if (!GetActualDeleteCount(cx, args, obj, len, actualStart, insertCount,
3513 &actualDeleteCount)) {
3514 return false;
3515 }
3516 MOZ_ASSERT(actualStart + actualDeleteCount <= len);
3517
3518 // Step 11. Let newLen be len + insertCount - actualDeleteCount.
3519 uint64_t newLen = len + insertCount - actualDeleteCount;
3520
3521 // Step 12 handled by GetActualDeleteCount().
3522 MOZ_ASSERT(newLen < DOUBLE_INTEGRAL_PRECISION_LIMIT);
3523 MOZ_ASSERT(actualStart <= newLen,
3524 "if |actualStart + actualDeleteCount <= len| and "
3525 "|newLen = len + insertCount - actualDeleteCount|, then "
3526 "|actualStart <= newLen|");
3527
3528 // ArrayCreate, step 1.
3529 if (newLen > UINT32_MAX) {
3530 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3531 JSMSG_BAD_ARRAY_LENGTH);
3532 return false;
3533 }
3534
3535 // Step 13. Let A be ? ArrayCreate(𝔽(newLen)).
3536 Rooted<ArrayObject*> arr(cx,
3537 NewDensePartlyAllocatedArray(cx, uint32_t(newLen)));
3538 if (!arr) {
3539 return false;
3540 }
3541
3542 // Steps 14-19 optimized for dense elements.
3543 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, len)) {
3544 MOZ_ASSERT(len <= UINT32_MAX);
3545 MOZ_ASSERT(actualDeleteCount <= UINT32_MAX,
3546 "if |actualStart + actualDeleteCount <= len| and "
3547 "|len <= UINT32_MAX|, then |actualDeleteCount <= UINT32_MAX|");
3548
3549 uint32_t length = uint32_t(len);
3550 uint32_t newLength = uint32_t(newLen);
3551 uint32_t start = uint32_t(actualStart);
3552 uint32_t deleteCount = uint32_t(actualDeleteCount);
3553
3554 auto nobj = obj.as<NativeObject>();
3555
3556 ArrayObject* arr = NewDenseFullyAllocatedArray(cx, newLength);
3557 if (!arr) {
3558 return false;
3559 }
3560
3561 // Below code doesn't handle the case when the storage has to grow,
3562 // therefore the capacity must fit for at least |newLength| elements.
3563 MOZ_ASSERT(arr->getDenseCapacity() >= newLength);
3564
3565 if (deleteCount == 0 && insertCount == 0) {
3566 // Copy the array when we don't have to remove or insert any elements.
3567 if (newLength > 0) {
3568 CopyDenseElementsFillHoles(arr, nobj, newLength);
3569 }
3570 } else {
3571 // Copy nobj[0..start] to arr[0..start].
3572 if (start > 0) {
3573 CopyDenseElementsFillHoles(arr, nobj, start);
3574 }
3575
3576 // Insert |items| into arr[start..(start + insertCount)].
3577 if (insertCount > 0) {
3578 auto items = HandleValueArray::subarray(args, 2, insertCount);
3579
3580 // Prefer |initDenseElements| because it's faster.
3581 if (arr->getDenseInitializedLength() == 0) {
3582 arr->initDenseElements(items.begin(), items.length());
3583 } else {
3584 arr->ensureDenseInitializedLength(start, items.length());
3585 arr->copyDenseElements(start, items.begin(), items.length());
3586 }
3587 }
3588
3589 uint32_t fromIndex = start + deleteCount;
3590 uint32_t toIndex = start + insertCount;
3591 MOZ_ASSERT((length - fromIndex) == (newLength - toIndex),
3592 "Copies all remaining elements to the end");
3593
3594 // Copy nobj[(start + deleteCount)..length] to
3595 // arr[(start + insertCount)..newLength].
3596 if (fromIndex < length) {
3597 uint32_t end = std::min(length, nobj->getDenseInitializedLength());
3598 if (fromIndex < end) {
3599 uint32_t count = end - fromIndex;
3600 if (nobj->denseElementsArePacked()) {
3601 // Copy all dense elements when no holes are present.
3602 const Value* src = nobj->getDenseElements() + fromIndex;
3603 arr->ensureDenseInitializedLength(toIndex, count);
3604 arr->copyDenseElements(toIndex, src, count);
3605 fromIndex += count;
3606 toIndex += count;
3607 } else {
3608 arr->setDenseInitializedLength(toIndex + count);
3609
3610 // Handle each element separately to filter out holes.
3611 for (uint32_t i = 0; i < count; i++) {
3612 Value val = nobj->getDenseElement(fromIndex++);
3613 if (val.isMagic(JS_ELEMENTS_HOLE)) {
3614 val = UndefinedValue();
3615 }
3616 arr->initDenseElement(toIndex++, val);
3617 }
3618 }
3619 }
3620
3621 arr->setDenseInitializedLength(newLength);
3622
3623 // Fill trailing holes with undefined.
3624 while (fromIndex < length) {
3625 arr->initDenseElement(toIndex++, UndefinedValue());
3626 fromIndex++;
3627 }
3628 }
3629
3630 MOZ_ASSERT(fromIndex == length);
3631 MOZ_ASSERT(toIndex == newLength);
3632 }
3633
3634 // Ensure the result array is packed and has the correct length.
3635 MOZ_ASSERT(IsPackedArray(arr));
3636 MOZ_ASSERT(arr->length() == newLength);
3637
3638 args.rval().setObject(*arr);
3639 return true;
3640 }
3641
3642 // Copy everything before start
3643
3644 // Step 14. Let i be 0.
3645 uint32_t i = 0;
3646
3647 // Step 15. Let r be actualStart + actualDeleteCount.
3648 uint64_t r = actualStart + actualDeleteCount;
3649
3650 // Step 16. Repeat while i < actualStart,
3651 RootedValue iValue(cx);
3652 while (i < uint32_t(actualStart)) {
3653 if (!CheckForInterrupt(cx)) {
3654 return false;
3655 }
3656
3657 // Skip Step 16.a. Let Pi be ! ToString(𝔽(i)).
3658
3659 // Step 16.b. Let iValue be ? Get(O, Pi).
3660 if (!GetArrayElement(cx, obj, i, &iValue)) {
3661 return false;
3662 }
3663
3664 // Step 16.c. Perform ! CreateDataPropertyOrThrow(A, Pi, iValue).
3665 if (!DefineArrayElement(cx, arr, i, iValue)) {
3666 return false;
3667 }
3668
3669 // Step 16.d. Set i to i + 1.
3670 i++;
3671 }
3672
3673 // Result array now contains all elements before start.
3674
3675 // Copy new items
3676 if (insertCount > 0) {
3677 HandleValueArray items = HandleValueArray::subarray(args, 2, insertCount);
3678
3679 // Fast-path to copy all items in one go.
3680 DenseElementResult result =
3681 arr->setOrExtendDenseElements(cx, i, items.begin(), items.length());
3682 if (result == DenseElementResult::Failure) {
3683 return false;
3684 }
3685
3686 if (result == DenseElementResult::Success) {
3687 i += items.length();
3688 } else {
3689 MOZ_ASSERT(result == DenseElementResult::Incomplete);
3690
3691 // Step 17. For each element E of items, do
3692 for (size_t j = 0; j < items.length(); j++) {
3693 if (!CheckForInterrupt(cx)) {
3694 return false;
3695 }
3696
3697 // Skip Step 17.a. Let Pi be ! ToString(𝔽(i)).
3698
3699 // Step 17.b. Perform ! CreateDataPropertyOrThrow(A, Pi, E).
3700 if (!DefineArrayElement(cx, arr, i, items[j])) {
3701 return false;
3702 }
3703
3704 // Step 17.c. Set i to i + 1.
3705 i++;
3706 }
3707 }
3708 }
3709
3710 // Copy items after new items
3711 // Step 18. Repeat, while i < newLen,
3712 RootedValue fromValue(cx);
3713 while (i < uint32_t(newLen)) {
3714 if (!CheckForInterrupt(cx)) {
3715 return false;
3716 }
3717
3718 // Skip Step 18.a. Let Pi be ! ToString(𝔽(i)).
3719 // Skip Step 18.b. Let from be ! ToString(𝔽(r)).
3720
3721 // Step 18.c. Let fromValue be ? Get(O, from). */
3722 if (!GetArrayElement(cx, obj, r, &fromValue)) {
3723 return false;
3724 }
3725
3726 // Step 18.d. Perform ! CreateDataPropertyOrThrow(A, Pi, fromValue).
3727 if (!DefineArrayElement(cx, arr, i, fromValue)) {
3728 return false;
3729 }
3730
3731 // Step 18.e. Set i to i + 1.
3732 i++;
3733
3734 // Step 18.f. Set r to r + 1.
3735 r++;
3736 }
3737
3738 // Step 19. Return A.
3739 args.rval().setObject(*arr);
3740 return true;
3741 }
3742
3743 // ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b
3744 // Array.prototype.with ( index, value )
3745 static bool array_with(JSContext* cx, unsigned argc, Value* vp) {
3746 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "with");
3747 CallArgs args = CallArgsFromVp(argc, vp);
3748
3749 // Step 1. Let O be ? ToObject(this value).
3750 RootedObject obj(cx, ToObject(cx, args.thisv()));
3751 if (!obj) {
3752 return false;
3753 }
3754
3755 // Step 2. Let len be ? LengthOfArrayLike(O).
3756 uint64_t len;
3757 if (!GetLengthPropertyInlined(cx, obj, &len)) {
3758 return false;
3759 }
3760
3761 // Step 3. Let relativeIndex be ? ToIntegerOrInfinity(index).
3762 double relativeIndex;
3763 if (!ToInteger(cx, args.get(0), &relativeIndex)) {
3764 return false;
3765 }
3766
3767 // Step 4. If relativeIndex >= 0, let actualIndex be relativeIndex.
3768 double actualIndex = relativeIndex;
3769 if (actualIndex < 0) {
3770 // Step 5. Else, let actualIndex be len + relativeIndex.
3771 actualIndex = double(len) + actualIndex;
3772 }
3773
3774 // Step 6. If actualIndex >= len or actualIndex < 0, throw a RangeError
3775 // exception.
3776 if (actualIndex < 0 || actualIndex >= double(len)) {
3777 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_INDEX);
3778 return false;
3779 }
3780
3781 // ArrayCreate, step 1.
3782 if (len > UINT32_MAX) {
3783 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3784 JSMSG_BAD_ARRAY_LENGTH);
3785 return false;
3786 }
3787 uint32_t length = uint32_t(len);
3788
3789 MOZ_ASSERT(length > 0);
3790 MOZ_ASSERT(0 <= actualIndex && actualIndex < UINT32_MAX);
3791
3792 // Steps 7-10 optimized for dense elements.
3793 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, length)) {
3794 auto nobj = obj.as<NativeObject>();
3795
3796 ArrayObject* arr = NewDenseFullyAllocatedArray(cx, length);
3797 if (!arr) {
3798 return false;
3799 }
3800
3801 CopyDenseElementsFillHoles(arr, nobj, length);
3802
3803 // Replace the value at |actualIndex|.
3804 arr->setDenseElement(uint32_t(actualIndex), args.get(1));
3805
3806 // Ensure the result array is packed and has the correct length.
3807 MOZ_ASSERT(IsPackedArray(arr));
3808 MOZ_ASSERT(arr->length() == length);
3809
3810 args.rval().setObject(*arr);
3811 return true;
3812 }
3813
3814 // Step 7. Let A be ? ArrayCreate(𝔽(len)).
3815 RootedObject arr(cx, NewDensePartlyAllocatedArray(cx, length));
3816 if (!arr) {
3817 return false;
3818 }
3819
3820 // Steps 8-9. Let k be 0; Repeat, while k < len,
3821 RootedValue fromValue(cx);
3822 for (uint32_t k = 0; k < length; k++) {
3823 if (!CheckForInterrupt(cx)) {
3824 return false;
3825 }
3826
3827 // Skip Step 9.a. Let Pk be ! ToString(𝔽(k)).
3828
3829 // Step 9.b. If k is actualIndex, let fromValue be value.
3830 if (k == uint32_t(actualIndex)) {
3831 fromValue = args.get(1);
3832 } else {
3833 // Step 9.c. Else, let fromValue be ? Get(O, 𝔽(k)).
3834 if (!GetArrayElement(cx, obj, k, &fromValue)) {
3835 return false;
3836 }
3837 }
3838
3839 // Step 9.d. Perform ! CreateDataPropertyOrThrow(A, 𝔽(k), fromValue).
3840 if (!DefineArrayElement(cx, arr, k, fromValue)) {
3841 return false;
3842 }
3843 }
3844
3845 // Step 10. Return A.
3846 args.rval().setObject(*arr);
3847 return true;
3848 }
3849
3850 struct SortComparatorIndexes {
3851 bool operator()(uint32_t a, uint32_t b, bool* lessOrEqualp) {
3852 *lessOrEqualp = (a <= b);
3853 return true;
3854 }
3855 };
3856
3857 // Returns all indexed properties in the range [begin, end) found on |obj| or
3858 // its proto chain. This function does not handle proxies, objects with
3859 // resolve/lookupProperty hooks or indexed getters, as those can introduce
3860 // new properties. In those cases, *success is set to |false|.
3861 static bool GetIndexedPropertiesInRange(JSContext* cx, HandleObject obj,
3862 uint64_t begin, uint64_t end,
3863 Vector<uint32_t>& indexes,
3864 bool* success) {
3865 *success = false;
3866
3867 // TODO: Add IdIsIndex with support for large indices.
3868 if (end > UINT32_MAX) {
3869 return true;
3870 }
3871 MOZ_ASSERT(begin <= UINT32_MAX);
3872
3873 // First, look for proxies or class hooks that can introduce extra
3874 // properties.
3875 JSObject* pobj = obj;
3876 do {
3877 if (!pobj->is<NativeObject>() || pobj->getClass()->getResolve() ||
3878 pobj->getOpsLookupProperty()) {
3879 return true;
3880 }
3881 } while ((pobj = pobj->staticPrototype()));
3882
3883 // Collect indexed property names.
3884 pobj = obj;
3885 do {
3886 // Append dense elements.
3887 NativeObject* nativeObj = &pobj->as<NativeObject>();
3888 uint32_t initLen = nativeObj->getDenseInitializedLength();
3889 for (uint32_t i = begin; i < initLen && i < end; i++) {
3890 if (nativeObj->getDenseElement(i).isMagic(JS_ELEMENTS_HOLE)) {
3891 continue;
3892 }
3893 if (!indexes.append(i)) {
3894 return false;
3895 }
3896 }
3897
3898 // Append typed array elements.
3899 if (nativeObj->is<TypedArrayObject>()) {
3900 size_t len = nativeObj->as<TypedArrayObject>().length().valueOr(0);
3901 for (uint32_t i = begin; i < len && i < end; i++) {
3902 if (!indexes.append(i)) {
3903 return false;
3904 }
3905 }
3906 }
3907
3908 // Append sparse elements.
3909 if (nativeObj->isIndexed()) {
3910 ShapePropertyIter<NoGC> iter(nativeObj->shape());
3911 for (; !iter.done(); iter++) {
3912 jsid id = iter->key();
3913 uint32_t i;
3914 if (!IdIsIndex(id, &i)) {
3915 continue;
3916 }
3917
3918 if (!(begin <= i && i < end)) {
3919 continue;
3920 }
3921
3922 // Watch out for getters, they can add new properties.
3923 if (!iter->isDataProperty()) {
3924 return true;
3925 }
3926
3927 if (!indexes.append(i)) {
3928 return false;
3929 }
3930 }
3931 }
3932 } while ((pobj = pobj->staticPrototype()));
3933
3934 // Sort the indexes.
3935 Vector<uint32_t> tmp(cx);
3936 size_t n = indexes.length();
3937 if (!tmp.resize(n)) {
3938 return false;
3939 }
3940 if (!MergeSort(indexes.begin(), n, tmp.begin(), SortComparatorIndexes())) {
3941 return false;
3942 }
3943
3944 // Remove duplicates.
3945 if (!indexes.empty()) {
3946 uint32_t last = 0;
3947 for (size_t i = 1, len = indexes.length(); i < len; i++) {
3948 uint32_t elem = indexes[i];
3949 if (indexes[last] != elem) {
3950 last++;
3951 indexes[last] = elem;
3952 }
3953 }
3954 if (!indexes.resize(last + 1)) {
3955 return false;
3956 }
3957 }
3958
3959 *success = true;
3960 return true;
3961 }
3962
3963 static bool SliceSparse(JSContext* cx, HandleObject obj, uint64_t begin,
3964 uint64_t end, Handle<ArrayObject*> result) {
3965 MOZ_ASSERT(begin <= end);
3966
3967 Vector<uint32_t> indexes(cx);
3968 bool success;
3969 if (!GetIndexedPropertiesInRange(cx, obj, begin, end, indexes, &success)) {
3970 return false;
3971 }
3972
3973 if (!success) {
3974 return CopyArrayElements(cx, obj, begin, end - begin, result);
3975 }
3976
3977 MOZ_ASSERT(end <= UINT32_MAX,
3978 "indices larger than UINT32_MAX should be rejected by "
3979 "GetIndexedPropertiesInRange");
3980
3981 RootedValue value(cx);
3982 for (uint32_t index : indexes) {
3983 MOZ_ASSERT(begin <= index && index < end);
3984
3985 bool hole;
3986 if (!HasAndGetElement(cx, obj, index, &hole, &value)) {
3987 return false;
3988 }
3989
3990 if (!hole &&
3991 !DefineDataElement(cx, result, index - uint32_t(begin), value)) {
3992 return false;
3993 }
3994 }
3995
3996 return true;
3997 }
3998
3999 static JSObject* SliceArguments(JSContext* cx, Handle<ArgumentsObject*> argsobj,
4000 uint32_t begin, uint32_t count) {
4001 MOZ_ASSERT(!argsobj->hasOverriddenLength() &&
4002 !argsobj->hasOverriddenElement());
4003 MOZ_ASSERT(begin + count <= argsobj->initialLength());
4004
4005 ArrayObject* result = NewDenseFullyAllocatedArray(cx, count);
4006 if (!result) {
4007 return nullptr;
4008 }
4009 result->setDenseInitializedLength(count);
4010
4011 for (uint32_t index = 0; index < count; index++) {
4012 const Value& v = argsobj->element(begin + index);
4013 result->initDenseElement(index, v);
4014 }
4015 return result;
4016 }
4017
4018 static bool ArraySliceOrdinary(JSContext* cx, HandleObject obj, uint64_t begin,
4019 uint64_t end, MutableHandleValue rval) {
4020 if (begin > end) {
4021 begin = end;
4022 }
4023
4024 if ((end - begin) > UINT32_MAX) {
4025 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4026 JSMSG_BAD_ARRAY_LENGTH);
4027 return false;
4028 }
4029 uint32_t count = uint32_t(end - begin);
4030
4031 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, end)) {
4032 MOZ_ASSERT(begin <= UINT32_MAX,
4033 "if end <= UINT32_MAX, then begin <= UINT32_MAX");
4034 JSObject* narr = CopyDenseArrayElements(cx, obj.as<NativeObject>(),
4035 uint32_t(begin), count);
4036 if (!narr) {
4037 return false;
4038 }
4039
4040 rval.setObject(*narr);
4041 return true;
4042 }
4043
4044 if (obj->is<ArgumentsObject>()) {
4045 Handle<ArgumentsObject*> argsobj = obj.as<ArgumentsObject>();
4046 if (!argsobj->hasOverriddenLength() && !argsobj->hasOverriddenElement()) {
4047 MOZ_ASSERT(begin <= UINT32_MAX, "begin is limited by |argsobj|'s length");
4048 JSObject* narr = SliceArguments(cx, argsobj, uint32_t(begin), count);
4049 if (!narr) {
4050 return false;
4051 }
4052
4053 rval.setObject(*narr);
4054 return true;
4055 }
4056 }
4057
4058 Rooted<ArrayObject*> narr(cx, NewDensePartlyAllocatedArray(cx, count));
4059 if (!narr) {
4060 return false;
4061 }
4062
4063 if (end <= UINT32_MAX) {
4064 if (js::GetElementsOp op = obj->getOpsGetElements()) {
4065 ElementAdder adder(cx, narr, count,
4066 ElementAdder::CheckHasElemPreserveHoles);
4067 if (!op(cx, obj, uint32_t(begin), uint32_t(end), &adder)) {
4068 return false;
4069 }
4070
4071 rval.setObject(*narr);
4072 return true;
4073 }
4074 }
4075
4076 if (obj->is<NativeObject>() && obj->as<NativeObject>().isIndexed() &&
4077 count > 1000) {
4078 if (!SliceSparse(cx, obj, begin, end, narr)) {
4079 return false;
4080 }
4081 } else {
4082 if (!CopyArrayElements(cx, obj, begin, count, narr)) {
4083 return false;
4084 }
4085 }
4086
4087 rval.setObject(*narr);
4088 return true;
4089 }
4090
4091 /* ES 2016 draft Mar 25, 2016 22.1.3.23. */
4092 static bool array_slice(JSContext* cx, unsigned argc, Value* vp) {
4093 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "slice");
4094 CallArgs args = CallArgsFromVp(argc, vp);
4095
4096 /* Step 1. */
4097 RootedObject obj(cx, ToObject(cx, args.thisv()));
4098 if (!obj) {
4099 return false;
4100 }
4101
4102 /* Step 2. */
4103 uint64_t length;
4104 if (!GetLengthPropertyInlined(cx, obj, &length)) {
4105 return false;
4106 }
4107
4108 /* Steps 3-4. */
4109 uint64_t k = 0;
4110 if (args.hasDefined(0)) {
4111 if (!ToIntegerIndex(cx, args[0], length, &k)) {
4112 return false;
4113 }
4114 }
4115
4116 /* Steps 5-6. */
4117 uint64_t final = length;
4118 if (args.hasDefined(1)) {
4119 if (!ToIntegerIndex(cx, args[1], length, &final)) {
4120 return false;
4121 }
4122 }
4123
4124 if (IsArraySpecies(cx, obj)) {
4125 /* Steps 7-12: Optimized for ordinary array. */
4126 return ArraySliceOrdinary(cx, obj, k, final, args.rval());
4127 }
4128
4129 /* Step 7. */
4130 uint64_t count = final > k ? final - k : 0;
4131
4132 /* Step 8. */
4133 RootedObject arr(cx);
4134 if (!ArraySpeciesCreate(cx, obj, count, &arr)) {
4135 return false;
4136 }
4137
4138 /* Step 9. */
4139 uint64_t n = 0;
4140
4141 /* Step 10. */
4142 RootedValue kValue(cx);
4143 while (k < final) {
4144 if (!CheckForInterrupt(cx)) {
4145 return false;
4146 }
4147
4148 /* Steps 10.a-b, and 10.c.i. */
4149 bool kNotPresent;
4150 if (!HasAndGetElement(cx, obj, k, &kNotPresent, &kValue)) {
4151 return false;
4152 }
4153
4154 /* Step 10.c. */
4155 if (!kNotPresent) {
4156 /* Steps 10.c.ii. */
4157 if (!DefineArrayElement(cx, arr, n, kValue)) {
4158 return false;
4159 }
4160 }
4161 /* Step 10.d. */
4162 k++;
4163
4164 /* Step 10.e. */
4165 n++;
4166 }
4167
4168 /* Step 11. */
4169 if (!SetLengthProperty(cx, arr, n)) {
4170 return false;
4171 }
4172
4173 /* Step 12. */
4174 args.rval().setObject(*arr);
4175 return true;
4176 }
4177
4178 static inline uint32_t NormalizeSliceTerm(int32_t value, uint32_t length) {
4179 if (value >= 0) {
4180 return std::min(uint32_t(value), length);
4181 }
4182 return uint32_t(std::max(int32_t(uint32_t(value) + length), 0));
4183 }
4184
4185 static bool ArraySliceDenseKernel(JSContext* cx, ArrayObject* arr,
4186 int32_t beginArg, int32_t endArg,
4187 ArrayObject* result) {
4188 uint32_t length = arr->length();
4189
4190 uint32_t begin = NormalizeSliceTerm(beginArg, length);
4191 uint32_t end = NormalizeSliceTerm(endArg, length);
4192
4193 if (begin > end) {
4194 begin = end;
4195 }
4196
4197 uint32_t count = end - begin;
4198 size_t initlen = arr->getDenseInitializedLength();
4199 if (initlen > begin) {
4200 uint32_t newlength = std::min<uint32_t>(initlen - begin, count);
4201 if (newlength > 0) {
4202 if (!result->ensureElements(cx, newlength)) {
4203 return false;
4204 }
4205 result->initDenseElements(arr, begin, newlength);
4206 }
4207 }
4208
4209 MOZ_ASSERT(count >= result->length());
4210 result->setLength(cx, count);
4211
4212 return true;
4213 }
4214
4215 JSObject* js::ArraySliceDense(JSContext* cx, HandleObject obj, int32_t begin,
4216 int32_t end, HandleObject result) {
4217 MOZ_ASSERT(IsPackedArray(obj));
4218
4219 if (result && IsArraySpecies(cx, obj)) {
4220 if (!ArraySliceDenseKernel(cx, &obj->as<ArrayObject>(), begin, end,
4221 &result->as<ArrayObject>())) {
4222 return nullptr;
4223 }
4224 return result;
4225 }
4226
4227 // Slower path if the JIT wasn't able to allocate an object inline.
4228 JS::RootedValueArray<4> argv(cx);
4229 argv[0].setUndefined();
4230 argv[1].setObject(*obj);
4231 argv[2].setInt32(begin);
4232 argv[3].setInt32(end);
4233 if (!array_slice(cx, 2, argv.begin())) {
4234 return nullptr;
4235 }
4236 return &argv[0].toObject();
4237 }
4238
4239 JSObject* js::ArgumentsSliceDense(JSContext* cx, HandleObject obj,
4240 int32_t begin, int32_t end,
4241 HandleObject result) {
4242 MOZ_ASSERT(obj->is<ArgumentsObject>());
4243 MOZ_ASSERT(IsArraySpecies(cx, obj));
4244
4245 Handle<ArgumentsObject*> argsobj = obj.as<ArgumentsObject>();
4246 MOZ_ASSERT(!argsobj->hasOverriddenLength());
4247 MOZ_ASSERT(!argsobj->hasOverriddenElement());
4248
4249 uint32_t length = argsobj->initialLength();
4250 uint32_t actualBegin = NormalizeSliceTerm(begin, length);
4251 uint32_t actualEnd = NormalizeSliceTerm(end, length);
4252
4253 if (actualBegin > actualEnd) {
4254 actualBegin = actualEnd;
4255 }
4256 uint32_t count = actualEnd - actualBegin;
4257
4258 if (result) {
4259 Handle<ArrayObject*> resArray = result.as<ArrayObject>();
4260 MOZ_ASSERT(resArray->getDenseInitializedLength() == 0);
4261 MOZ_ASSERT(resArray->length() == 0);
4262
4263 if (count > 0) {
4264 if (!resArray->ensureElements(cx, count)) {
4265 return nullptr;
4266 }
4267 resArray->setDenseInitializedLength(count);
4268 resArray->setLengthToInitializedLength();
4269
4270 for (uint32_t index = 0; index < count; index++) {
4271 const Value& v = argsobj->element(actualBegin + index);
4272 resArray->initDenseElement(index, v);
4273 }
4274 }
4275
4276 return resArray;
4277 }
4278
4279 // Slower path if the JIT wasn't able to allocate an object inline.
4280 return SliceArguments(cx, argsobj, actualBegin, count);
4281 }
4282
4283 static bool array_isArray(JSContext* cx, unsigned argc, Value* vp) {
4284 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array", "isArray");
4285 CallArgs args = CallArgsFromVp(argc, vp);
4286
4287 bool isArray = false;
4288 if (args.get(0).isObject()) {
4289 RootedObject obj(cx, &args[0].toObject());
4290 if (!IsArray(cx, obj, &isArray)) {
4291 return false;
4292 }
4293 }
4294 args.rval().setBoolean(isArray);
4295 return true;
4296 }
4297
4298 static bool ArrayFromCallArgs(JSContext* cx, CallArgs& args,
4299 HandleObject proto = nullptr) {
4300 ArrayObject* obj =
4301 NewDenseCopiedArrayWithProto(cx, args.length(), args.array(), proto);
4302 if (!obj) {
4303 return false;
4304 }
4305
4306 args.rval().setObject(*obj);
4307 return true;
4308 }
4309
4310 static bool array_of(JSContext* cx, unsigned argc, Value* vp) {
4311 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array", "of");
4312 CallArgs args = CallArgsFromVp(argc, vp);
4313
4314 bool isArrayConstructor =
4315 IsArrayConstructor(args.thisv()) &&
4316 args.thisv().toObject().nonCCWRealm() == cx->realm();
4317
4318 if (isArrayConstructor || !IsConstructor(args.thisv())) {
4319 // isArrayConstructor will usually be true in practice. This is the most
4320 // common path.
4321 return ArrayFromCallArgs(cx, args);
4322 }
4323
4324 // Step 4.
4325 RootedObject obj(cx);
4326 {
4327 FixedConstructArgs<1> cargs(cx);
4328
4329 cargs[0].setNumber(args.length());
4330
4331 if (!Construct(cx, args.thisv(), cargs, args.thisv(), &obj)) {
4332 return false;
4333 }
4334 }
4335
4336 // Step 8.
4337 for (unsigned k = 0; k < args.length(); k++) {
4338 if (!DefineDataElement(cx, obj, k, args[k])) {
4339 return false;
4340 }
4341 }
4342
4343 // Steps 9-10.
4344 if (!SetLengthProperty(cx, obj, args.length())) {
4345 return false;
4346 }
4347
4348 // Step 11.
4349 args.rval().setObject(*obj);
4350 return true;
4351 }
4352
4353 static const JSJitInfo array_splice_info = {
4354 {(JSJitGetterOp)array_splice_noRetVal},
4355 {0}, /* unused */
4356 {0}, /* unused */
4357 JSJitInfo::IgnoresReturnValueNative,
4358 JSJitInfo::AliasEverything,
4359 JSVAL_TYPE_UNDEFINED,
4360 };
4361
4362 enum class SearchKind {
4363 // Specializes SearchElementDense for Array.prototype.indexOf/lastIndexOf.
4364 // This means hole values are ignored and StrictlyEqual semantics are used.
4365 IndexOf,
4366 // Specializes SearchElementDense for Array.prototype.includes.
4367 // This means hole values are treated as |undefined| and SameValueZero
4368 // semantics are used.
4369 Includes,
4370 };
4371
4372 template <SearchKind Kind, typename Iter>
4373 static bool SearchElementDense(JSContext* cx, HandleValue val, Iter iterator,
4374 MutableHandleValue rval) {
4375 // We assume here and in the iterator lambdas that nothing can trigger GC or
4376 // move dense elements.
4377 AutoCheckCannotGC nogc;
4378
4379 // Fast path for string values.
4380 if (val.isString()) {
4381 JSLinearString* str = val.toString()->ensureLinear(cx);
4382 if (!str) {
4383 return false;
4384 }
4385 const uint32_t strLen = str->length();
4386 auto cmp = [str, strLen](JSContext* cx, const Value& element, bool* equal) {
4387 if (!element.isString() || element.toString()->length() != strLen) {
4388 *equal = false;
4389 return true;
4390 }
4391 JSLinearString* s = element.toString()->ensureLinear(cx);
4392 if (!s) {
4393 return false;
4394 }
4395 *equal = EqualStrings(str, s);
4396 return true;
4397 };
4398 return iterator(cx, cmp, rval);
4399 }
4400
4401 // Fast path for numbers.
4402 if (val.isNumber()) {
4403 double dval = val.toNumber();
4404 // For |includes|, two NaN values are considered equal, so we use a
4405 // different implementation for NaN.
4406 if (Kind == SearchKind::Includes && std::isnan(dval)) {
4407 auto cmp = [](JSContext*, const Value& element, bool* equal) {
4408 *equal = (element.isDouble() && std::isnan(element.toDouble()));
4409 return true;
4410 };
4411 return iterator(cx, cmp, rval);
4412 }
4413 auto cmp = [dval](JSContext*, const Value& element, bool* equal) {
4414 *equal = (element.isNumber() && element.toNumber() == dval);
4415 return true;
4416 };
4417 return iterator(cx, cmp, rval);
4418 }
4419
4420 // Fast path for values where we can use a simple bitwise comparison.
4421 if (CanUseBitwiseCompareForStrictlyEqual(val)) {
4422 // For |includes| we need to treat hole values as |undefined| so we use a
4423 // different path if searching for |undefined|.
4424 if (Kind == SearchKind::Includes && val.isUndefined()) {
4425 auto cmp = [](JSContext*, const Value& element, bool* equal) {
4426 *equal = (element.isUndefined() || element.isMagic(JS_ELEMENTS_HOLE));
4427 return true;
4428 };
4429 return iterator(cx, cmp, rval);
4430 }
4431 uint64_t bits = val.asRawBits();
4432 auto cmp = [bits](JSContext*, const Value& element, bool* equal) {
4433 *equal = (bits == element.asRawBits());
4434 return true;
4435 };
4436 return iterator(cx, cmp, rval);
4437 }
4438
4439 MOZ_ASSERT(val.isBigInt());
4440
4441 // Generic implementation for the remaining types.
4442 RootedValue elementRoot(cx);
4443 auto cmp = [val, &elementRoot](JSContext* cx, const Value& element,
4444 bool* equal) {
4445 if (MOZ_UNLIKELY(element.isMagic(JS_ELEMENTS_HOLE))) {
4446 // |includes| treats holes as |undefined|, but |undefined| is already
4447 // handled above. For |indexOf| we have to ignore holes.
4448 *equal = false;
4449 return true;
4450 }
4451 // Note: |includes| uses SameValueZero, but that checks for NaN and then
4452 // calls StrictlyEqual. Since we already handled NaN above, we can call
4453 // StrictlyEqual directly.
4454 MOZ_ASSERT(!val.isNumber());
4455 elementRoot = element;
4456 return StrictlyEqual(cx, val, elementRoot, equal);
4457 };
4458 return iterator(cx, cmp, rval);
4459 }
4460
4461 // ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b
4462 // 23.1.3.17 Array.prototype.indexOf ( searchElement [ , fromIndex ] )
4463 bool js::array_indexOf(JSContext* cx, unsigned argc, Value* vp) {
4464 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "indexOf");
4465 CallArgs args = CallArgsFromVp(argc, vp);
4466
4467 // Step 1.
4468 RootedObject obj(cx, ToObject(cx, args.thisv()));
4469 if (!obj) {
4470 return false;
4471 }
4472
4473 // Step 2.
4474 uint64_t len;
4475 if (!GetLengthPropertyInlined(cx, obj, &len)) {
4476 return false;
4477 }
4478
4479 // Step 3.
4480 if (len == 0) {
4481 args.rval().setInt32(-1);
4482 return true;
4483 }
4484
4485 // Steps 4-9.
4486 uint64_t k = 0;
4487 if (args.hasDefined(1)) {
4488 if (!ToIntegerIndex(cx, args[1], len, &k)) {
4489 return false;
4490 }
4491
4492 // Return early if |k| exceeds the current length.
4493 if (k >= len) {
4494 args.rval().setInt32(-1);
4495 return true;
4496 }
4497 }
4498
4499 MOZ_ASSERT(k < len);
4500
4501 HandleValue searchElement = args.get(0);
4502
4503 // Step 10 optimized for dense elements.
4504 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, len)) {
4505 MOZ_ASSERT(len <= UINT32_MAX);
4506
4507 NativeObject* nobj = &obj->as<NativeObject>();
4508 uint32_t start = uint32_t(k);
4509 uint32_t length =
4510 std::min(nobj->getDenseInitializedLength(), uint32_t(len));
4511 const Value* elements = nobj->getDenseElements();
4512
4513 if (CanUseBitwiseCompareForStrictlyEqual(searchElement) && length > start) {
4514 const uint64_t* elementsAsBits =
4515 reinterpret_cast<const uint64_t*>(elements);
4516 const uint64_t* res = SIMD::memchr64(
4517 elementsAsBits + start, searchElement.asRawBits(), length - start);
4518 if (res) {
4519 args.rval().setInt32(static_cast<int32_t>(res - elementsAsBits));
4520 } else {
4521 args.rval().setInt32(-1);
4522 }
4523 return true;
4524 }
4525
4526 auto iterator = [elements, start, length](JSContext* cx, auto cmp,
4527 MutableHandleValue rval) {
4528 static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT <= INT32_MAX,
4529 "code assumes dense index fits in Int32Value");
4530 for (uint32_t i = start; i < length; i++) {
4531 bool equal;
4532 if (MOZ_UNLIKELY(!cmp(cx, elements[i], &equal))) {
4533 return false;
4534 }
4535 if (equal) {
4536 rval.setInt32(int32_t(i));
4537 return true;
4538 }
4539 }
4540 rval.setInt32(-1);
4541 return true;
4542 };
4543 return SearchElementDense<SearchKind::IndexOf>(cx, searchElement, iterator,
4544 args.rval());
4545 }
4546
4547 // Step 10.
4548 RootedValue v(cx);
4549 for (; k < len; k++) {
4550 if (!CheckForInterrupt(cx)) {
4551 return false;
4552 }
4553
4554 bool hole;
4555 if (!HasAndGetElement(cx, obj, k, &hole, &v)) {
4556 return false;
4557 }
4558 if (hole) {
4559 continue;
4560 }
4561
4562 bool equal;
4563 if (!StrictlyEqual(cx, v, searchElement, &equal)) {
4564 return false;
4565 }
4566 if (equal) {
4567 args.rval().setNumber(k);
4568 return true;
4569 }
4570 }
4571
4572 // Step 11.
4573 args.rval().setInt32(-1);
4574 return true;
4575 }
4576
4577 // ES2020 draft rev dc1e21c454bd316810be1c0e7af0131a2d7f38e9
4578 // 22.1.3.17 Array.prototype.lastIndexOf ( searchElement [ , fromIndex ] )
4579 bool js::array_lastIndexOf(JSContext* cx, unsigned argc, Value* vp) {
4580 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "lastIndexOf");
4581 CallArgs args = CallArgsFromVp(argc, vp);
4582
4583 // Step 1.
4584 RootedObject obj(cx, ToObject(cx, args.thisv()));
4585 if (!obj) {
4586 return false;
4587 }
4588
4589 // Step 2.
4590 uint64_t len;
4591 if (!GetLengthPropertyInlined(cx, obj, &len)) {
4592 return false;
4593 }
4594
4595 // Step 3.
4596 if (len == 0) {
4597 args.rval().setInt32(-1);
4598 return true;
4599 }
4600
4601 // Steps 4-6.
4602 uint64_t k = len - 1;
4603 if (args.length() > 1) {
4604 double n;
4605 if (!ToInteger(cx, args[1], &n)) {
4606 return false;
4607 }
4608
4609 // Steps 5-6.
4610 if (n < 0) {
4611 double d = double(len) + n;
4612 if (d < 0) {
4613 args.rval().setInt32(-1);
4614 return true;
4615 }
4616 k = uint64_t(d);
4617 } else if (n < double(k)) {
4618 k = uint64_t(n);
4619 }
4620 }
4621
4622 MOZ_ASSERT(k < len);
4623
4624 HandleValue searchElement = args.get(0);
4625
4626 // Steps 7 and 8 optimized for dense elements.
4627 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, k + 1)) {
4628 MOZ_ASSERT(k <= UINT32_MAX);
4629
4630 NativeObject* nobj = &obj->as<NativeObject>();
4631 uint32_t initLen = nobj->getDenseInitializedLength();
4632 if (initLen == 0) {
4633 args.rval().setInt32(-1);
4634 return true;
4635 }
4636
4637 uint32_t end = std::min(uint32_t(k), initLen - 1);
4638 const Value* elements = nobj->getDenseElements();
4639
4640 auto iterator = [elements, end](JSContext* cx, auto cmp,
4641 MutableHandleValue rval) {
4642 static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT <= INT32_MAX,
4643 "code assumes dense index fits in int32_t");
4644 for (int32_t i = int32_t(end); i >= 0; i--) {
4645 bool equal;
4646 if (MOZ_UNLIKELY(!cmp(cx, elements[i], &equal))) {
4647 return false;
4648 }
4649 if (equal) {
4650 rval.setInt32(int32_t(i));
4651 return true;
4652 }
4653 }
4654 rval.setInt32(-1);
4655 return true;
4656 };
4657 return SearchElementDense<SearchKind::IndexOf>(cx, searchElement, iterator,
4658 args.rval());
4659 }
4660
4661 // Step 7.
4662 RootedValue v(cx);
4663 for (int64_t i = int64_t(k); i >= 0; i--) {
4664 if (!CheckForInterrupt(cx)) {
4665 return false;
4666 }
4667
4668 bool hole;
4669 if (!HasAndGetElement(cx, obj, uint64_t(i), &hole, &v)) {
4670 return false;
4671 }
4672 if (hole) {
4673 continue;
4674 }
4675
4676 bool equal;
4677 if (!StrictlyEqual(cx, v, searchElement, &equal)) {
4678 return false;
4679 }
4680 if (equal) {
4681 args.rval().setNumber(uint64_t(i));
4682 return true;
4683 }
4684 }
4685
4686 // Step 8.
4687 args.rval().setInt32(-1);
4688 return true;
4689 }
4690
4691 // ES2026 draft rev a562082b031d89d00ee667181ce8a6158656bd4b
4692 // 23.1.3.16 Array.prototype.includes ( searchElement [ , fromIndex ] )
4693 bool js::array_includes(JSContext* cx, unsigned argc, Value* vp) {
4694 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "includes");
4695 CallArgs args = CallArgsFromVp(argc, vp);
4696
4697 // Step 1.
4698 RootedObject obj(cx, ToObject(cx, args.thisv()));
4699 if (!obj) {
4700 return false;
4701 }
4702
4703 // Step 2.
4704 uint64_t len;
4705 if (!GetLengthPropertyInlined(cx, obj, &len)) {
4706 return false;
4707 }
4708
4709 // Step 3.
4710 if (len == 0) {
4711 args.rval().setBoolean(false);
4712 return true;
4713 }
4714
4715 // Steps 4-9.
4716 uint64_t k = 0;
4717 if (args.hasDefined(1)) {
4718 if (!ToIntegerIndex(cx, args[1], len, &k)) {
4719 return false;
4720 }
4721
4722 // Return early if |k| exceeds the current length.
4723 if (k >= len) {
4724 args.rval().setBoolean(false);
4725 return true;
4726 }
4727 }
4728
4729 MOZ_ASSERT(k < len);
4730
4731 HandleValue searchElement = args.get(0);
4732
4733 // Step 10 optimized for dense elements.
4734 if (CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, len)) {
4735 MOZ_ASSERT(len <= UINT32_MAX);
4736
4737 NativeObject* nobj = &obj->as<NativeObject>();
4738 uint32_t start = uint32_t(k);
4739 uint32_t length =
4740 std::min(nobj->getDenseInitializedLength(), uint32_t(len));
4741 const Value* elements = nobj->getDenseElements();
4742
4743 // Trailing holes are treated as |undefined|.
4744 if (uint32_t(len) > length && searchElement.isUndefined()) {
4745 // |undefined| is strictly equal only to |undefined|.
4746 args.rval().setBoolean(true);
4747 return true;
4748 }
4749
4750 // For |includes| we need to treat hole values as |undefined| so we use a
4751 // different path if searching for |undefined|.
4752 if (CanUseBitwiseCompareForStrictlyEqual(searchElement) &&
4753 !searchElement.isUndefined() && length > start) {
4754 if (SIMD::memchr64(reinterpret_cast<const uint64_t*>(elements) + start,
4755 searchElement.asRawBits(), length - start)) {
4756 args.rval().setBoolean(true);
4757 } else {
4758 args.rval().setBoolean(false);
4759 }
4760 return true;
4761 }
4762
4763 auto iterator = [elements, start, length](JSContext* cx, auto cmp,
4764 MutableHandleValue rval) {
4765 for (uint32_t i = start; i < length; i++) {
4766 bool equal;
4767 if (MOZ_UNLIKELY(!cmp(cx, elements[i], &equal))) {
4768 return false;
4769 }
4770 if (equal) {
4771 rval.setBoolean(true);
4772 return true;
4773 }
4774 }
4775 rval.setBoolean(false);
4776 return true;
4777 };
4778 return SearchElementDense<SearchKind::Includes>(cx, searchElement, iterator,
4779 args.rval());
4780 }
4781
4782 // Step 10.
4783 RootedValue v(cx);
4784 for (; k < len; k++) {
4785 if (!CheckForInterrupt(cx)) {
4786 return false;
4787 }
4788
4789 if (!GetArrayElement(cx, obj, k, &v)) {
4790 return false;
4791 }
4792
4793 bool equal;
4794 if (!SameValueZero(cx, v, searchElement, &equal)) {
4795 return false;
4796 }
4797 if (equal) {
4798 args.rval().setBoolean(true);
4799 return true;
4800 }
4801 }
4802
4803 // Step 11.
4804 args.rval().setBoolean(false);
4805 return true;
4806 }
4807
4808 // ES2024 draft 23.1.3.2.1 IsConcatSpreadable
4809 static bool IsConcatSpreadable(JSContext* cx, HandleValue v, bool* spreadable) {
4810 // Step 1.
4811 if (!v.isObject()) {
4812 *spreadable = false;
4813 return true;
4814 }
4815
4816 // Step 2.
4817 JS::Symbol* sym = cx->wellKnownSymbols().isConcatSpreadable;
4818 JSObject* holder;
4819 if (MOZ_UNLIKELY(
4820 MaybeHasInterestingSymbolProperty(cx, &v.toObject(), sym, &holder))) {
4821 RootedValue res(cx);
4822 RootedObject obj(cx, holder);
4823 Rooted<PropertyKey> key(cx, PropertyKey::Symbol(sym));
4824 if (!GetProperty(cx, obj, v, key, &res)) {
4825 return false;
4826 }
4827 // Step 3.
4828 if (!res.isUndefined()) {
4829 *spreadable = ToBoolean(res);
4830 return true;
4831 }
4832 }
4833
4834 // Step 4.
4835 if (MOZ_LIKELY(v.toObject().is<ArrayObject>())) {
4836 *spreadable = true;
4837 return true;
4838 }
4839 RootedObject obj(cx, &v.toObject());
4840 bool isArray;
4841 if (!JS::IsArray(cx, obj, &isArray)) {
4842 return false;
4843 }
4844 *spreadable = isArray;
4845 return true;
4846 }
4847
4848 // Returns true if the object may have an @@isConcatSpreadable property.
4849 static bool MaybeHasIsConcatSpreadable(JSContext* cx, JSObject* obj) {
4850 JS::Symbol* sym = cx->wellKnownSymbols().isConcatSpreadable;
4851 JSObject* holder;
4852 return MaybeHasInterestingSymbolProperty(cx, obj, sym, &holder);
4853 }
4854
4855 static bool TryOptimizePackedArrayConcat(JSContext* cx, CallArgs& args,
4856 Handle<JSObject*> obj,
4857 bool* optimized) {
4858 // Fast path for the following cases:
4859 //
4860 // (1) packedArray.concat(): copy the array's elements.
4861 // (2) packedArray.concat(packedArray): concatenate two packed arrays.
4862 // (3) packedArray.concat(value): copy and append a single non-array value.
4863 //
4864 // These cases account for almost all calls to Array.prototype.concat in
4865 // Speedometer 3.
4866
4867 *optimized = false;
4868
4869 if (args.length() > 1) {
4870 return true;
4871 }
4872
4873 // The `this` object must be a packed array without @@isConcatSpreadable.
4874 // @@isConcatSpreadable is uncommon and requires a property lookup and more
4875 // complicated code, so we let the slow path handle it.
4876 if (!IsPackedArray(obj)) {
4877 return true;
4878 }
4879 if (MaybeHasIsConcatSpreadable(cx, obj)) {
4880 return true;
4881 }
4882
4883 Handle<ArrayObject*> thisArr = obj.as<ArrayObject>();
4884 uint32_t thisLen = thisArr->length();
4885
4886 if (args.length() == 0) {
4887 // Case (1). Copy the packed array.
4888 ArrayObject* arr = NewDenseFullyAllocatedArray(cx, thisLen);
4889 if (!arr) {
4890 return false;
4891 }
4892 arr->initDenseElements(thisArr->getDenseElements(), thisLen);
4893 args.rval().setObject(*arr);
4894 *optimized = true;
4895 return true;
4896 }
4897
4898 MOZ_ASSERT(args.length() == 1);
4899
4900 // If the argument is an object, it must not have an @@isConcatSpreadable
4901 // property.
4902 if (args[0].isObject() &&
4903 MaybeHasIsConcatSpreadable(cx, &args[0].toObject())) {
4904 return true;
4905 }
4906
4907 MOZ_ASSERT_IF(args[0].isObject(), args[0].toObject().is<NativeObject>());
4908
4909 // Case (3). Copy and append a single value if the argument is not an array.
4910 if (!args[0].isObject() || !args[0].toObject().is<ArrayObject>()) {
4911 ArrayObject* arr = NewDenseFullyAllocatedArray(cx, thisLen + 1);
4912 if (!arr) {
4913 return false;
4914 }
4915 arr->initDenseElements(thisArr->getDenseElements(), thisLen);
4916
4917 arr->ensureDenseInitializedLength(thisLen, 1);
4918 arr->initDenseElement(thisLen, args[0]);
4919
4920 args.rval().setObject(*arr);
4921 *optimized = true;
4922 return true;
4923 }
4924
4925 // Case (2). Concatenate two packed arrays.
4926 if (!IsPackedArray(&args[0].toObject())) {
4927 return true;
4928 }
4929
4930 uint32_t argLen = args[0].toObject().as<ArrayObject>().length();
4931
4932 // Compute the array length. This can't overflow because both arrays are
4933 // packed.
4934 static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT < INT32_MAX);
4935 MOZ_ASSERT(thisLen <= NativeObject::MAX_DENSE_ELEMENTS_COUNT);
4936 MOZ_ASSERT(argLen <= NativeObject::MAX_DENSE_ELEMENTS_COUNT);
4937 uint32_t totalLen = thisLen + argLen;
4938
4939 ArrayObject* arr = NewDenseFullyAllocatedArray(cx, totalLen);
4940 if (!arr) {
4941 return false;
4942 }
4943 arr->initDenseElements(thisArr->getDenseElements(), thisLen);
4944
4945 ArrayObject* argArr = &args[0].toObject().as<ArrayObject>();
4946 arr->ensureDenseInitializedLength(thisLen, argLen);
4947 arr->initDenseElementRange(thisLen, argArr, argLen);
4948
4949 args.rval().setObject(*arr);
4950 *optimized = true;
4951 return true;
4952 }
4953
4954 static bool array_concat(JSContext* cx, unsigned argc, Value* vp) {
4955 AutoJSMethodProfilerEntry pseudoFrame(cx, "Array.prototype", "concat");
4956 CallArgs args = CallArgsFromVp(argc, vp);
4957
4958 // Step 1.
4959 RootedObject obj(cx, ToObject(cx, args.thisv()));
4960 if (!obj) {
4961 return false;
4962 }
4963
4964 bool isArraySpecies = IsArraySpecies(cx, obj);
4965
4966 // Fast path for the most common cases.
4967 if (isArraySpecies) {
4968 bool optimized;
4969 if (!TryOptimizePackedArrayConcat(cx, args, obj, &optimized)) {
4970 return false;
4971 }
4972 if (optimized) {
4973 return true;
4974 }
4975 }
4976
4977 // Step 2.
4978 RootedObject arr(cx);
4979 if (isArraySpecies) {
4980 arr = NewDenseEmptyArray(cx);
4981 if (!arr) {
4982 return false;
4983 }
4984 } else {
4985 if (!ArraySpeciesCreate(cx, obj, 0, &arr)) {
4986 return false;
4987 }
4988 }
4989
4990 // Step 3.
4991 uint64_t n = 0;
4992
4993 // Step 4 (handled implicitly with nextArg and CallArgs).
4994 uint32_t nextArg = 0;
4995
4996 // Step 5.
4997 RootedValue v(cx, ObjectValue(*obj));
4998 while (true) {
4999 // Step 5.a.
5000 bool spreadable;
5001 if (!IsConcatSpreadable(cx, v, &spreadable)) {
5002 return false;
5003 }
5004 // Step 5.b.
5005 if (spreadable) {
5006 // Step 5.b.i.
5007 obj = &v.toObject();
5008 uint64_t len;
5009 if (!GetLengthPropertyInlined(cx, obj, &len)) {
5010 return false;
5011 }
5012
5013 // Step 5.b.ii.
5014 if (n + len > uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT) - 1) {
5015 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5016 JSMSG_TOO_LONG_ARRAY);
5017 return false;
5018 }
5019
5020 // Step 5.b.iii.
5021 uint64_t k = 0;
5022
5023 // Step 5.b.iv.
5024
5025 // Try a fast path for copying dense elements directly.
5026 bool optimized = false;
5027 if (len > 0 && isArraySpecies &&
5028 CanOptimizeForDenseStorage<ArrayAccess::Read>(obj, len) &&
5029 n + len <= NativeObject::MAX_DENSE_ELEMENTS_COUNT) {
5030 NativeObject* nobj = &obj->as<NativeObject>();
5031 ArrayObject* resArr = &arr->as<ArrayObject>();
5032 uint32_t count =
5033 std::min(uint32_t(len), nobj->getDenseInitializedLength());
5034
5035 DenseElementResult res = resArr->ensureDenseElements(cx, n, count);
5036 if (res == DenseElementResult::Failure) {
5037 return false;
5038 }
5039 if (res == DenseElementResult::Success) {
5040 resArr->initDenseElementRange(n, nobj, count);
5041 n += len;
5042 optimized = true;
5043 } else {
5044 MOZ_ASSERT(res == DenseElementResult::Incomplete);
5045 }
5046 }
5047
5048 if (!optimized) {
5049 // Step 5.b.iv.
5050 while (k < len) {
5051 if (!CheckForInterrupt(cx)) {
5052 return false;
5053 }
5054
5055 // Step 5.b.iv.2.
5056 bool hole;
5057 if (!HasAndGetElement(cx, obj, k, &hole, &v)) {
5058 return false;
5059 }
5060 if (!hole) {
5061 // Step 5.b.iv.3.
5062 if (!DefineArrayElement(cx, arr, n, v)) {
5063 return false;
5064 }
5065 }
5066
5067 // Step 5.b.iv.4.
5068 n++;
5069
5070 // Step 5.b.iv.5.
5071 k++;
5072 }
5073 }
5074 } else {
5075 // Step 5.c.ii.
5076 if (n >= uint64_t(DOUBLE_INTEGRAL_PRECISION_LIMIT) - 1) {
5077 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5078 JSMSG_TOO_LONG_ARRAY);
5079 return false;
5080 }
5081
5082 // Step 5.c.iii.
5083 if (!DefineArrayElement(cx, arr, n, v)) {
5084 return false;
5085 }
5086
5087 // Step 5.c.iv.
5088 n++;
5089 }
5090
5091 // Move on to the next argument.
5092 if (nextArg == args.length()) {
5093 break;
5094 }
5095 v = args[nextArg];
5096 nextArg++;
5097 }
5098
5099 // Step 6.
5100 if (!SetLengthProperty(cx, arr, n)) {
5101 return false;
5102 }
5103
5104 // Step 7.
5105 args.rval().setObject(*arr);
5106 return true;
5107 }
5108
5109 static const JSFunctionSpec array_methods[] = {
5110 JS_FN("toSource", array_toSource, 0, 0),
5111 JS_SELF_HOSTED_FN("toString", "ArrayToString", 0, 0),
5112 JS_FN("toLocaleString", array_toLocaleString, 0, 0),
5113
5114 /* Perl-ish methods. */
5115 JS_INLINABLE_FN("join", array_join, 1, 0, ArrayJoin),
5116 JS_FN("reverse", array_reverse, 0, 0),
5117 JS_TRAMPOLINE_FN("sort", array_sort, 1, 0, ArraySort),
5118 JS_INLINABLE_FN("push", array_push, 1, 0, ArrayPush),
5119 JS_INLINABLE_FN("pop", array_pop, 0, 0, ArrayPop),
5120 JS_INLINABLE_FN("shift", array_shift, 0, 0, ArrayShift),
5121 JS_FN("unshift", array_unshift, 1, 0),
5122 JS_FNINFO("splice", array_splice, &array_splice_info, 2, 0),
5123
5124 /* Pythonic sequence methods. */
5125 JS_FN("concat", array_concat, 1, 0),
5126 JS_INLINABLE_FN("slice", array_slice, 2, 0, ArraySlice),
5127
5128 JS_FN("lastIndexOf", array_lastIndexOf, 1, 0),
5129 JS_FN("indexOf", array_indexOf, 1, 0),
5130 JS_SELF_HOSTED_FN("forEach", "ArrayForEach", 1, 0),
5131 JS_SELF_HOSTED_FN("map", "ArrayMap", 1, 0),
5132 JS_SELF_HOSTED_FN("filter", "ArrayFilter", 1, 0),
5133 JS_SELF_HOSTED_FN("reduce", "ArrayReduce", 1, 0),
5134 JS_SELF_HOSTED_FN("reduceRight", "ArrayReduceRight", 1, 0),
5135 JS_SELF_HOSTED_FN("some", "ArraySome", 1, 0),
5136 JS_SELF_HOSTED_FN("every", "ArrayEvery", 1, 0),
5137
5138 /* ES6 additions */
5139 JS_SELF_HOSTED_FN("find", "ArrayFind", 1, 0),
5140 JS_SELF_HOSTED_FN("findIndex", "ArrayFindIndex", 1, 0),
5141 JS_SELF_HOSTED_FN("copyWithin", "ArrayCopyWithin", 3, 0),
5142
5143 JS_SELF_HOSTED_FN("fill", "ArrayFill", 3, 0),
5144
5145 JS_SELF_HOSTED_SYM_FN(iterator, "$ArrayValues", 0, 0),
5146 JS_SELF_HOSTED_FN("entries", "ArrayEntries", 0, 0),
5147 JS_SELF_HOSTED_FN("keys", "ArrayKeys", 0, 0),
5148 JS_SELF_HOSTED_FN("values", "$ArrayValues", 0, 0),
5149
5150 /* ES7 additions */
5151 JS_FN("includes", array_includes, 1, 0),
5152
5153 /* ES2020 */
5154 JS_SELF_HOSTED_FN("flatMap", "ArrayFlatMap", 1, 0),
5155 JS_SELF_HOSTED_FN("flat", "ArrayFlat", 0, 0),
5156
5157 JS_SELF_HOSTED_FN("at", "ArrayAt", 1, 0),
5158 JS_SELF_HOSTED_FN("findLast", "ArrayFindLast", 1, 0),
5159 JS_SELF_HOSTED_FN("findLastIndex", "ArrayFindLastIndex", 1, 0),
5160
5161 JS_SELF_HOSTED_FN("toReversed", "ArrayToReversed", 0, 0),
5162 JS_SELF_HOSTED_FN("toSorted", "ArrayToSorted", 1, 0),
5163 JS_FN("toSpliced", array_toSpliced, 2, 0),
5164 JS_FN("with", array_with, 2, 0),
5165
5166 JS_FS_END,
5167 };
5168
5169 static const JSFunctionSpec array_static_methods[] = {
5170 JS_INLINABLE_FN("isArray", array_isArray, 1, 0, ArrayIsArray),
5171 JS_SELF_HOSTED_FN("from", "ArrayFrom", 3, 0),
5172 JS_SELF_HOSTED_FN("fromAsync", "ArrayFromAsync", 3, 0),
5173 JS_FN("of", array_of, 0, 0),
5174
5175 JS_FS_END,
5176 };
5177
5178 const JSPropertySpec array_static_props[] = {
5179 JS_SELF_HOSTED_SYM_GET(species, "$ArraySpecies", 0),
5180 JS_PS_END,
5181 };
5182
5183 static inline bool ArrayConstructorImpl(JSContext* cx, CallArgs& args,
5184 bool isConstructor) {
5185 RootedObject proto(cx);
5186 if (isConstructor) {
5187 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Array, &proto)) {
5188 return false;
5189 }
5190 }
5191
5192 if (args.length() != 1 || !args[0].isNumber()) {
5193 return ArrayFromCallArgs(cx, args, proto);
5194 }
5195
5196 uint32_t length;
5197 if (args[0].isInt32()) {
5198 int32_t i = args[0].toInt32();
5199 if (i < 0) {
5200 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5201 JSMSG_BAD_ARRAY_LENGTH);
5202 return false;
5203 }
5204 length = uint32_t(i);
5205 } else {
5206 double d = args[0].toDouble();
5207 length = ToUint32(d);
5208 if (d != double(length)) {
5209 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5210 JSMSG_BAD_ARRAY_LENGTH);
5211 return false;
5212 }
5213 }
5214
5215 ArrayObject* obj = NewDensePartlyAllocatedArrayWithProto(cx, length, proto);
5216 if (!obj) {
5217 return false;
5218 }
5219
5220 args.rval().setObject(*obj);
5221 return true;
5222 }
5223
5224 /* ES5 15.4.2 */
5225 bool js::ArrayConstructor(JSContext* cx, unsigned argc, Value* vp) {
5226 AutoJSConstructorProfilerEntry pseudoFrame(cx, "Array");
5227 CallArgs args = CallArgsFromVp(argc, vp);
5228 return ArrayConstructorImpl(cx, args, /* isConstructor = */ true);
5229 }
5230
5231 bool js::array_construct(JSContext* cx, unsigned argc, Value* vp) {
5232 AutoJSConstructorProfilerEntry pseudoFrame(cx, "Array");
5233 CallArgs args = CallArgsFromVp(argc, vp);
5234 MOZ_ASSERT(!args.isConstructing());
5235 MOZ_ASSERT(args.length() == 1);
5236 MOZ_ASSERT(args[0].isNumber());
5237 return ArrayConstructorImpl(cx, args, /* isConstructor = */ false);
5238 }
5239
5240 ArrayObject* js::ArrayConstructorOneArg(JSContext* cx,
5241 Handle<ArrayObject*> templateObject,
5242 int32_t lengthInt,
5243 gc::AllocSite* site) {
5244 // JIT code can call this with a template object from a different realm when
5245 // calling another realm's Array constructor.
5246 Maybe<AutoRealm> ar;
5247 if (cx->realm() != templateObject->realm()) {
5248 MOZ_ASSERT(cx->compartment() == templateObject->compartment());
5249 ar.emplace(cx, templateObject);
5250 }
5251
5252 if (lengthInt < 0) {
5253 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5254 JSMSG_BAD_ARRAY_LENGTH);
5255 return nullptr;
5256 }
5257
5258 uint32_t length = uint32_t(lengthInt);
5259 ArrayObject* res =
5260 NewDensePartlyAllocatedArray(cx, length, GenericObject, site);
5261 MOZ_ASSERT_IF(res, res->realm() == templateObject->realm());
5262 return res;
5263 }
5264
5265 /*
5266 * Array allocation functions.
5267 */
5268
5269 static inline bool EnsureNewArrayElements(JSContext* cx, ArrayObject* obj,
5270 uint32_t length) {
5271 /*
5272 * If ensureElements creates dynamically allocated slots, then having
5273 * fixedSlots is a waste.
5274 */
5275 DebugOnly<uint32_t> cap = obj->getDenseCapacity();
5276
5277 if (!obj->ensureElements(cx, length)) {
5278 return false;
5279 }
5280
5281 MOZ_ASSERT_IF(cap, !obj->hasDynamicElements());
5282
5283 return true;
5284 }
5285
5286 template <uint32_t maxLength>
5287 static MOZ_ALWAYS_INLINE ArrayObject* NewArrayWithShape(
5288 JSContext* cx, Handle<SharedShape*> shape, uint32_t length,
5289 NewObjectKind newKind, gc::AllocSite* site = nullptr) {
5290 // The shape must already have the |length| property defined on it.
5291 MOZ_ASSERT(shape->propMapLength() == 1);
5292 MOZ_ASSERT(shape->lastProperty().key() == NameToId(cx->names().length));
5293
5294 gc::AllocKind allocKind = GuessArrayGCKind(length);
5295 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
5296 gc::FinalizeKind::None);
5297 MOZ_ASSERT(!IsFinalizedKind(allocKind));
5298
5299 MOZ_ASSERT(shape->slotSpan() == 0);
5300 constexpr uint32_t slotSpan = 0;
5301
5302 AutoSetNewObjectMetadata metadata(cx);
5303 ArrayObject* arr = ArrayObject::create(
5304 cx, allocKind, GetInitialHeap(newKind, &ArrayObject::class_, site), shape,
5305 length, slotSpan, metadata, site);
5306 if (!arr) {
5307 return nullptr;
5308 }
5309
5310 if (maxLength > 0 &&
5311 !EnsureNewArrayElements(cx, arr, std::min(maxLength, length))) {
5312 return nullptr;
5313 }
5314
5315 probes::CreateObject(cx, arr);
5316 return arr;
5317 }
5318
5319 static SharedShape* GetArrayShapeWithProto(JSContext* cx, HandleObject proto) {
5320 // Get a shape with zero fixed slots, because arrays store the ObjectElements
5321 // header inline.
5322 Rooted<SharedShape*> shape(
5323 cx, SharedShape::getInitialShape(cx, &ArrayObject::class_, cx->realm(),
5324 TaggedProto(proto), /* nfixed = */ 0));
5325 if (!shape) {
5326 return nullptr;
5327 }
5328
5329 // Add the |length| property and use the new shape as initial shape for new
5330 // arrays.
5331 if (shape->propMapLength() == 0) {
5332 shape = AddLengthProperty(cx, shape);
5333 if (!shape) {
5334 return nullptr;
5335 }
5336 SharedShape::insertInitialShape(cx, shape);
5337 } else {
5338 MOZ_ASSERT(shape->propMapLength() == 1);
5339 MOZ_ASSERT(shape->lastProperty().key() == NameToId(cx->names().length));
5340 }
5341
5342 return shape;
5343 }
5344
5345 SharedShape* GlobalObject::createArrayShapeWithDefaultProto(JSContext* cx) {
5346 MOZ_ASSERT(!cx->global()->data().arrayShapeWithDefaultProto);
5347
5348 RootedObject proto(cx,
5349 GlobalObject::getOrCreateArrayPrototype(cx, cx->global()));
5350 if (!proto) {
5351 return nullptr;
5352 }
5353
5354 SharedShape* shape = GetArrayShapeWithProto(cx, proto);
5355 if (!shape) {
5356 return nullptr;
5357 }
5358
5359 cx->global()->data().arrayShapeWithDefaultProto.init(shape);
5360 return shape;
5361 }
5362
5363 template <uint32_t maxLength>
5364 static MOZ_ALWAYS_INLINE ArrayObject* NewArray(JSContext* cx, uint32_t length,
5365 NewObjectKind newKind,
5366 gc::AllocSite* site = nullptr) {
5367 Rooted<SharedShape*> shape(cx,
5368 GlobalObject::getArrayShapeWithDefaultProto(cx));
5369 if (!shape) {
5370 return nullptr;
5371 }
5372
5373 return NewArrayWithShape<maxLength>(cx, shape, length, newKind, site);
5374 }
5375
5376 template <uint32_t maxLength>
5377 static MOZ_ALWAYS_INLINE ArrayObject* NewArrayWithProto(JSContext* cx,
5378 uint32_t length,
5379 HandleObject proto,
5380 NewObjectKind newKind) {
5381 Rooted<SharedShape*> shape(cx);
5382 if (!proto || proto == cx->global()->maybeGetArrayPrototype()) {
5383 shape = GlobalObject::getArrayShapeWithDefaultProto(cx);
5384 } else {
5385 shape = GetArrayShapeWithProto(cx, proto);
5386 }
5387 if (!shape) {
5388 return nullptr;
5389 }
5390
5391 return NewArrayWithShape<maxLength>(cx, shape, length, newKind, nullptr);
5392 }
5393
5394 static JSObject* CreateArrayConstructor(JSContext* cx, JSProtoKey key) {
5395 MOZ_ASSERT(key == JSProto_Array);
5396 Rooted<JSObject*> ctor(cx, GlobalObject::createConstructor(
5397 cx, ArrayConstructor, cx->names().Array, 1,
5398 gc::AllocKind::FUNCTION, &jit::JitInfo_Array));
5399 if (!ctor) {
5400 return nullptr;
5401 }
5402 if (!JSObject::setHasFuseProperty(cx, ctor)) {
5403 return nullptr;
5404 }
5405 return ctor;
5406 }
5407
5408 static JSObject* CreateArrayPrototype(JSContext* cx, JSProtoKey key) {
5409 MOZ_ASSERT(key == JSProto_Array);
5410 RootedObject proto(cx, &cx->global()->getObjectPrototype());
5411 return NewArrayWithProto<0>(cx, 0, proto, TenuredObject);
5412 }
5413
5414 static bool array_proto_finish(JSContext* cx, JS::HandleObject ctor,
5415 JS::HandleObject proto) {
5416 // Add Array.prototype[@@unscopables]. ECMA-262 draft (2016 Mar 19) 22.1.3.32.
5417 RootedObject unscopables(cx,
5418 NewPlainObjectWithProto(cx, nullptr, TenuredObject));
5419 if (!unscopables) {
5420 return false;
5421 }
5422
5423 RootedValue value(cx, BooleanValue(true));
5424 if (!DefineDataProperty(cx, unscopables, cx->names().at, value) ||
5425 !DefineDataProperty(cx, unscopables, cx->names().copyWithin, value) ||
5426 !DefineDataProperty(cx, unscopables, cx->names().entries, value) ||
5427 !DefineDataProperty(cx, unscopables, cx->names().fill, value) ||
5428 !DefineDataProperty(cx, unscopables, cx->names().find, value) ||
5429 !DefineDataProperty(cx, unscopables, cx->names().findIndex, value) ||
5430 !DefineDataProperty(cx, unscopables, cx->names().findLast, value) ||
5431 !DefineDataProperty(cx, unscopables, cx->names().findLastIndex, value) ||
5432 !DefineDataProperty(cx, unscopables, cx->names().flat, value) ||
5433 !DefineDataProperty(cx, unscopables, cx->names().flatMap, value) ||
5434 !DefineDataProperty(cx, unscopables, cx->names().includes, value) ||
5435 !DefineDataProperty(cx, unscopables, cx->names().keys, value) ||
5436 !DefineDataProperty(cx, unscopables, cx->names().toReversed, value) ||
5437 !DefineDataProperty(cx, unscopables, cx->names().toSorted, value) ||
5438 !DefineDataProperty(cx, unscopables, cx->names().toSpliced, value) ||
5439 !DefineDataProperty(cx, unscopables, cx->names().values, value)) {
5440 return false;
5441 }
5442
5443 RootedId id(cx, PropertyKey::Symbol(cx->wellKnownSymbols().unscopables));
5444 value.setObject(*unscopables);
5445 if (!DefineDataProperty(cx, proto, id, value, JSPROP_READONLY)) {
5446 return false;
5447 }
5448
5449 // Mark Array prototype as having fuse property (@iterator for example).
5450 return JSObject::setHasFuseProperty(cx, proto);
5451 }
5452
5453 static const JSClassOps ArrayObjectClassOps = {
5454 array_addProperty, // addProperty
5455 nullptr, // delProperty
5456 nullptr, // enumerate
5457 nullptr, // newEnumerate
5458 nullptr, // resolve
5459 nullptr, // mayResolve
5460 nullptr, // finalize
5461 nullptr, // call
5462 nullptr, // construct
5463 nullptr, // trace
5464 };
5465
5466 static const ClassSpec ArrayObjectClassSpec = {
5467 CreateArrayConstructor, CreateArrayPrototype, array_static_methods,
5468 array_static_props, array_methods, nullptr,
5469 array_proto_finish,
5470 };
5471
5472 const JSClass ArrayObject::class_ = {
5473 "Array",
5474 JSCLASS_HAS_CACHED_PROTO(JSProto_Array) | JSCLASS_DELAY_METADATA_BUILDER,
5475 &ArrayObjectClassOps,
5476 &ArrayObjectClassSpec,
5477 };
5478
5479 ArrayObject* js::NewDenseEmptyArray(JSContext* cx) {
5480 return NewArray<0>(cx, 0, GenericObject);
5481 }
5482
5483 ArrayObject* js::NewTenuredDenseEmptyArray(JSContext* cx) {
5484 return NewArray<0>(cx, 0, TenuredObject);
5485 }
5486
5487 ArrayObject* js::NewDenseFullyAllocatedArray(
5488 JSContext* cx, uint32_t length, NewObjectKind newKind /* = GenericObject */,
5489 gc::AllocSite* site /* = nullptr */) {
5490 return NewArray<UINT32_MAX>(cx, length, newKind, site);
5491 }
5492
5493 ArrayObject* js::NewDensePartlyAllocatedArray(
5494 JSContext* cx, uint32_t length, NewObjectKind newKind /* = GenericObject */,
5495 gc::AllocSite* site /* = nullptr */) {
5496 return NewArray<ArrayObject::EagerAllocationMaxLength>(cx, length, newKind,
5497 site);
5498 }
5499
5500 ArrayObject* js::NewDensePartlyAllocatedArrayWithProto(JSContext* cx,
5501 uint32_t length,
5502 HandleObject proto) {
5503 return NewArrayWithProto<ArrayObject::EagerAllocationMaxLength>(
5504 cx, length, proto, GenericObject);
5505 }
5506
5507 ArrayObject* js::NewDenseUnallocatedArray(
5508 JSContext* cx, uint32_t length,
5509 NewObjectKind newKind /* = GenericObject */) {
5510 return NewArray<0>(cx, length, newKind);
5511 }
5512
5513 // values must point at already-rooted Value objects
5514 ArrayObject* js::NewDenseCopiedArray(
5515 JSContext* cx, uint32_t length, const Value* values,
5516 NewObjectKind newKind /* = GenericObject */) {
5517 ArrayObject* arr = NewArray<UINT32_MAX>(cx, length, newKind);
5518 if (!arr) {
5519 return nullptr;
5520 }
5521
5522 arr->initDenseElements(values, length);
5523 return arr;
5524 }
5525
5526 // values must point at already-rooted Value objects
5527 ArrayObject* js::NewDenseCopiedArray(
5528 JSContext* cx, uint32_t length, JSLinearString** values,
5529 NewObjectKind newKind /* = GenericObject */) {
5530 ArrayObject* arr = NewArray<UINT32_MAX>(cx, length, newKind);
5531 if (!arr) {
5532 return nullptr;
5533 }
5534
5535 arr->initDenseElements(values, length);
5536 return arr;
5537 }
5538
5539 ArrayObject* js::NewDenseCopiedArrayWithProto(JSContext* cx, uint32_t length,
5540 const Value* values,
5541 HandleObject proto) {
5542 ArrayObject* arr =
5543 NewArrayWithProto<UINT32_MAX>(cx, length, proto, GenericObject);
5544 if (!arr) {
5545 return nullptr;
5546 }
5547
5548 arr->initDenseElements(values, length);
5549 return arr;
5550 }
5551
5552 ArrayObject* js::NewDenseFullyAllocatedArrayWithShape(
5553 JSContext* cx, uint32_t length, Handle<SharedShape*> shape) {
5554 AutoSetNewObjectMetadata metadata(cx);
5555 gc::AllocKind allocKind = GuessArrayGCKind(length);
5556 MOZ_ASSERT(gc::GetObjectFinalizeKind(&ArrayObject::class_) ==
5557 gc::FinalizeKind::None);
5558 MOZ_ASSERT(!IsFinalizedKind(allocKind));
5559
5560 gc::Heap heap = GetInitialHeap(GenericObject, &ArrayObject::class_);
5561 ArrayObject* arr = ArrayObject::create(cx, allocKind, heap, shape, length,
5562 shape->slotSpan(), metadata);
5563 if (!arr) {
5564 return nullptr;
5565 }
5566
5567 if (!EnsureNewArrayElements(cx, arr, length)) {
5568 return nullptr;
5569 }
5570
5571 probes::CreateObject(cx, arr);
5572
5573 return arr;
5574 }
5575
5576 // TODO(no-TI): clean up.
5577 ArrayObject* js::NewArrayWithShape(JSContext* cx, uint32_t length,
5578 Handle<Shape*> shape) {
5579 // Ion can call this with a shape from a different realm when calling
5580 // another realm's Array constructor.
5581 Maybe<AutoRealm> ar;
5582 if (cx->realm() != shape->realm()) {
5583 MOZ_ASSERT(cx->compartment() == shape->compartment());
5584 ar.emplace(cx, shape);
5585 }
5586
5587 return NewDenseFullyAllocatedArray(cx, length);
5588 }
5589
5590 #ifdef DEBUG
5591 bool js::ArrayInfo(JSContext* cx, unsigned argc, Value* vp) {
5592 CallArgs args = CallArgsFromVp(argc, vp);
5593 RootedObject obj(cx);
5594
5595 for (unsigned i = 0; i < args.length(); i++) {
5596 HandleValue arg = args[i];
5597
5598 UniqueChars bytes =
5599 DecompileValueGenerator(cx, JSDVG_SEARCH_STACK, arg, nullptr);
5600 if (!bytes) {
5601 return false;
5602 }
5603 if (arg.isPrimitive() || !(obj = arg.toObjectOrNull())->is<ArrayObject>()) {
5604 fprintf(stderr, "%s: not array\n", bytes.get());
5605 continue;
5606 }
5607 fprintf(stderr, "%s: (len %u", bytes.get(),
5608 obj->as<ArrayObject>().length());
5609 fprintf(stderr, ", capacity %u", obj->as<ArrayObject>().getDenseCapacity());
5610 fputs(")\n", stderr);
5611 }
5612
5613 args.rval().setUndefined();
5614 return true;
5615 }
5616 #endif
5617
5618 JS_PUBLIC_API JSObject* JS::NewArrayObject(JSContext* cx,
5619 const HandleValueArray& contents) {
5620 MOZ_ASSERT(!cx->zone()->isAtomsZone());
5621 AssertHeapIsIdle();
5622 CHECK_THREAD(cx);
5623 cx->check(contents);
5624
5625 return NewDenseCopiedArray(cx, contents.length(), contents.begin());
5626 }
5627
5628 JS_PUBLIC_API JSObject* JS::NewArrayObject(JSContext* cx, size_t length) {
5629 MOZ_ASSERT(!cx->zone()->isAtomsZone());
5630 AssertHeapIsIdle();
5631 CHECK_THREAD(cx);
5632
5633 return NewDenseFullyAllocatedArray(cx, length);
5634 }
5635
5636 JS_PUBLIC_API bool JS::IsArrayObject(JSContext* cx, Handle<JSObject*> obj,
5637 bool* isArray) {
5638 return IsGivenTypeObject(cx, obj, ESClass::Array, isArray);
5639 }
5640
5641 JS_PUBLIC_API bool JS::IsArrayObject(JSContext* cx, Handle<Value> value,
5642 bool* isArray) {
5643 if (!value.isObject()) {
5644 *isArray = false;
5645 return true;
5646 }
5647
5648 Rooted<JSObject*> obj(cx, &value.toObject());
5649 return IsArrayObject(cx, obj, isArray);
5650 }
5651
5652 JS_PUBLIC_API bool JS::GetArrayLength(JSContext* cx, Handle<JSObject*> obj,
5653 uint32_t* lengthp) {
5654 AssertHeapIsIdle();
5655 CHECK_THREAD(cx);
5656 cx->check(obj);
5657
5658 uint64_t len = 0;
5659 if (!GetLengthProperty(cx, obj, &len)) {
5660 return false;
5661 }
5662
5663 if (len > UINT32_MAX) {
5664 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5665 JSMSG_BAD_ARRAY_LENGTH);
5666 return false;
5667 }
5668
5669 *lengthp = uint32_t(len);
5670 return true;
5671 }
5672
5673 JS_PUBLIC_API bool JS::SetArrayLength(JSContext* cx, Handle<JSObject*> obj,
5674 uint32_t length) {
5675 AssertHeapIsIdle();
5676 CHECK_THREAD(cx);
5677 cx->check(obj);
5678
5679 return SetLengthProperty(cx, obj, length);
5680 }
5681
5682 ArrayObject* js::NewArrayWithNullProto(JSContext* cx) {
5683 Rooted<SharedShape*> shape(cx, GetArrayShapeWithProto(cx, nullptr));
5684 if (!shape) {
5685 return nullptr;
5686 }
5687
5688 uint32_t length = 0;
5689 return ::NewArrayWithShape<0>(cx, shape, length, GenericObject);
5690 }