Debian Codegraph @

js/src/vm/Iteration.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 /* JavaScript iterators. */
8
9 #include "vm/Iteration.h"
10
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/Likely.h"
13 #include "mozilla/Maybe.h"
14 #include "mozilla/MemoryReporting.h"
15 #include "mozilla/PodOperations.h"
16
17 #include <algorithm>
18 #include <new>
19
20 #include "jsapi.h"
21 #include "jstypes.h"
22
23 #include "builtin/Array.h"
24 #include "builtin/MapObject.h"
25 #include "builtin/SelfHostingDefines.h"
26 #include "ds/Sort.h"
27 #include "gc/GC.h"
28 #include "gc/GCContext.h"
29 #include "js/ForOfIterator.h" // JS::ForOfIterator
30 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
31 #include "js/PropertySpec.h"
32 #include "util/DifferentialTesting.h"
33 #include "util/Poison.h"
34 #include "vm/GlobalObject.h"
35 #include "vm/Interpreter.h"
36 #include "vm/JSContext.h"
37 #include "vm/JSObject.h"
38 #include "vm/NativeObject.h" // js::PlainObject
39 #include "vm/Shape.h"
40 #include "vm/StringType.h"
41 #include "vm/TypedArrayObject.h"
42 #include "vm/Watchtower.h"
43 #include "vm/NativeObject-inl.h"
44 #include "vm/PlainObject-inl.h" // js::PlainObject::createWithTemplate
45 #include "vm/Shape-inl.h" // js::GetPropertyAttributes
46
47 using namespace js;
48
49 using mozilla::ArrayEqual;
50 using mozilla::Maybe;
51 using mozilla::PodCopy;
52
53 using RootedPropertyIteratorObject = Rooted<PropertyIteratorObject*>;
54
55 static const gc::AllocKind ITERATOR_FINALIZE_KIND =
56 gc::AllocKind::OBJECT2_BACKGROUND;
57
58 // Beware! This function may have to trace incompletely-initialized
59 // |NativeIterator| allocations if the |IdToString| in that constructor recurs
60 // into this code.
61 void NativeIterator::trace(JSTracer* trc) {
62 TraceNullableEdge(trc, &objectBeingIterated_, "objectBeingIterated_");
63 TraceNullableEdge(trc, &iterObj_, "iterObj");
64
65 // The limits below are correct at every instant of |NativeIterator|
66 // initialization, with the end-pointer incremented as each new shape is
67 // created, so they're safe to use here.
68 std::for_each(shapesBegin(), shapesEnd(), [trc](GCPtr<Shape*>& shape) {
69 TraceEdge(trc, &shape, "iterator_shape");
70 });
71
72 // But as properties must be created *before* shapes, |propertiesBegin()|
73 // that depends on |shapesEnd()| having its final value can't safely be
74 // used. Until this is fully initialized, use |propertyCursor_| instead,
75 // which points at the start of properties even in partially initialized
76 // |NativeIterator|s. (|propertiesEnd()| is safe at all times with respect
77 // to the properly-chosen beginning.)
78 //
79 // Note that we must trace all properties (not just those not yet visited,
80 // or just visited, due to |NativeIterator::previousPropertyWas|) for
81 // |NativeIterator|s to be reusable.
82 GCPtr<JSLinearString*>* begin =
83 MOZ_LIKELY(isInitialized()) ? propertiesBegin() : propertyCursor_;
84 std::for_each(begin, propertiesEnd(), [trc](GCPtr<JSLinearString*>& prop) {
85 // Properties begin life non-null and never *become*
86 // null. (Deletion-suppression will shift trailing
87 // properties over a deleted property in the properties
88 // array, but it doesn't null them out.)
89 TraceEdge(trc, &prop, "prop");
90 });
91 }
92
93 using PropertyKeySet = GCHashSet<PropertyKey, DefaultHasher<PropertyKey>>;
94
95 class PropertyEnumerator {
96 RootedObject obj_;
97 MutableHandleIdVector props_;
98 PropertyIndexVector* indices_;
99
100 uint32_t flags_;
101 Rooted<PropertyKeySet> visited_;
102
103 bool enumeratingProtoChain_ = false;
104
105 enum class IndicesState {
106 // Every property that has been enumerated so far can be represented as a
107 // PropertyIndex, but we are not currently producing a list of indices. If
108 // the state is Valid when we are done enumerating, then the resulting
109 // iterator can be marked as NativeIteratorIndices::AvailableOnRequest.
110 Valid,
111
112 // Every property that has been enumerated so far can be represented as a
113 // PropertyIndex, and |indices_| points to a PropertyIndexVector containing
114 // those indices. This is used when we want to create a NativeIterator with
115 // valid indices.
116 Allocating,
117
118 // It is not possible to represent every property of the object being
119 // enumerated as a PropertyIndex. For example, enumerated properties on the
120 // prototype chain are unsupported. We can transition to this state from
121 // either of the other two.
122 Unsupported
123 };
124 IndicesState indicesState_;
125
126 public:
127 PropertyEnumerator(JSContext* cx, JSObject* obj, uint32_t flags,
128 MutableHandleIdVector props,
129 PropertyIndexVector* indices = nullptr)
130 : obj_(cx, obj),
131 props_(props),
132 indices_(indices),
133 flags_(flags),
134 visited_(cx, PropertyKeySet(cx)),
135 indicesState_(indices ? IndicesState::Allocating
136 : IndicesState::Valid) {}
137
138 bool snapshot(JSContext* cx);
139
140 void markIndicesUnsupported() { indicesState_ = IndicesState::Unsupported; }
141 bool supportsIndices() const {
142 return indicesState_ != IndicesState::Unsupported;
143 }
144 bool allocatingIndices() const {
145 return indicesState_ == IndicesState::Allocating;
146 }
147
148 private:
149 template <bool CheckForDuplicates>
150 bool enumerate(JSContext* cx, jsid id, bool enumerable,
151 PropertyIndex index = PropertyIndex::Invalid());
152
153 bool enumerateExtraProperties(JSContext* cx);
154
155 template <bool CheckForDuplicates>
156 bool enumerateNativeProperties(JSContext* cx);
157
158 bool enumerateNativeProperties(JSContext* cx, bool checkForDuplicates) {
159 if (checkForDuplicates) {
160 return enumerateNativeProperties<true>(cx);
161 }
162 return enumerateNativeProperties<false>(cx);
163 }
164
165 template <bool CheckForDuplicates>
166 bool enumerateProxyProperties(JSContext* cx);
167
168 void reversePropsAndIndicesAfter(size_t initialLength) {
169 // We iterate through prop maps in descending order of property creation,
170 // but we need our return value to be in ascending order. If we are tracking
171 // property indices, make sure to keep them in sync.
172 MOZ_ASSERT(props_.begin() + initialLength <= props_.end());
173 MOZ_ASSERT_IF(allocatingIndices(), props_.length() == indices_->length());
174
175 std::reverse(props_.begin() + initialLength, props_.end());
176 if (allocatingIndices()) {
177 std::reverse(indices_->begin() + initialLength, indices_->end());
178 }
179 }
180 };
181
182 template <bool CheckForDuplicates>
183 bool PropertyEnumerator::enumerate(JSContext* cx, jsid id, bool enumerable,
184 PropertyIndex index) {
185 if (CheckForDuplicates) {
186 // If we've already seen this, we definitely won't add it.
187 PropertyKeySet::AddPtr p = visited_.lookupForAdd(id);
188 if (MOZ_UNLIKELY(!!p)) {
189 return true;
190 }
191
192 // It's not necessary to add properties to the hash set at the end of
193 // the prototype chain, but custom enumeration behaviors might return
194 // duplicated properties, so always add in such cases.
195 if (obj_->is<ProxyObject>() || obj_->staticPrototype() ||
196 obj_->getClass()->getNewEnumerate()) {
197 if (!visited_.add(p, id)) {
198 return false;
199 }
200 }
201 }
202
203 if (!enumerable && !(flags_ & JSITER_HIDDEN)) {
204 return true;
205 }
206
207 // Symbol-keyed properties and nonenumerable properties are skipped unless
208 // the caller specifically asks for them. A caller can also filter out
209 // non-symbols by asking for JSITER_SYMBOLSONLY. PrivateName symbols are
210 // skipped unless JSITER_PRIVATE is passed.
211 if (id.isSymbol()) {
212 if (!(flags_ & JSITER_SYMBOLS)) {
213 return true;
214 }
215 if (!(flags_ & JSITER_PRIVATE) && id.isPrivateName()) {
216 return true;
217 }
218 } else {
219 if ((flags_ & JSITER_SYMBOLSONLY)) {
220 return true;
221 }
222 }
223
224 MOZ_ASSERT_IF(allocatingIndices(), indices_->length() == props_.length());
225 if (!props_.append(id)) {
226 return false;
227 }
228
229 if (!supportsIndices()) {
230 return true;
231 }
232 if (index.kind() == PropertyIndex::Kind::Invalid || enumeratingProtoChain_) {
233 markIndicesUnsupported();
234 return true;
235 }
236
237 if (allocatingIndices() && !indices_->append(index)) {
238 return false;
239 }
240
241 return true;
242 }
243
244 bool PropertyEnumerator::enumerateExtraProperties(JSContext* cx) {
245 MOZ_ASSERT(obj_->getClass()->getNewEnumerate());
246
247 RootedIdVector properties(cx);
248 bool enumerableOnly = !(flags_ & JSITER_HIDDEN);
249 if (!obj_->getClass()->getNewEnumerate()(cx, obj_, &properties,
250 enumerableOnly)) {
251 return false;
252 }
253
254 RootedId id(cx);
255 for (size_t n = 0; n < properties.length(); n++) {
256 id = properties[n];
257
258 // The enumerate hook does not indicate whether the properties
259 // it returns are enumerable or not. Since we already passed
260 // `enumerableOnly` to the hook to filter out non-enumerable
261 // properties, it doesn't really matter what we pass here.
262 bool enumerable = true;
263 if (!enumerate<true>(cx, id, enumerable)) {
264 return false;
265 }
266 }
267
268 return true;
269 }
270
271 static bool SortComparatorIntegerIds(jsid a, jsid b, bool* lessOrEqualp) {
272 uint32_t indexA, indexB;
273 MOZ_ALWAYS_TRUE(IdIsIndex(a, &indexA));
274 MOZ_ALWAYS_TRUE(IdIsIndex(b, &indexB));
275 *lessOrEqualp = (indexA <= indexB);
276 return true;
277 }
278
279 template <bool CheckForDuplicates>
280 bool PropertyEnumerator::enumerateNativeProperties(JSContext* cx) {
281 Handle<NativeObject*> pobj = obj_.as<NativeObject>();
282
283 if (Watchtower::watchesPropertyValueChange(pobj)) {
284 markIndicesUnsupported();
285 }
286
287 // We don't need to iterate over the shape's properties if we're only
288 // interested in enumerable properties and the object is known to have no
289 // enumerable properties.
290 //
291 // Don't optimize if CheckForDuplicates is true, because non-enumerable
292 // properties still have to participate in duplicate-property checking.
293 const bool iterShapeProperties = CheckForDuplicates ||
294 (flags_ & JSITER_HIDDEN) ||
295 pobj->hasEnumerableProperty();
296
297 bool enumerateSymbols;
298 if (flags_ & JSITER_SYMBOLSONLY) {
299 if (!iterShapeProperties) {
300 return true;
301 }
302 enumerateSymbols = true;
303 } else {
304 // Collect any dense elements from this object.
305 size_t firstElemIndex = props_.length();
306 size_t initlen = pobj->getDenseInitializedLength();
307 const Value* elements = pobj->getDenseElements();
308 bool hasHoles = false;
309 for (uint32_t i = 0; i < initlen; ++i) {
310 if (elements[i].isMagic(JS_ELEMENTS_HOLE)) {
311 hasHoles = true;
312 } else {
313 // Dense arrays never get so large that i would not fit into an
314 // integer id.
315 if (!enumerate<CheckForDuplicates>(cx, PropertyKey::Int(i),
316 /* enumerable = */ true,
317 PropertyIndex::ForElement(i))) {
318 return false;
319 }
320 }
321 }
322
323 // Collect any typed array or shared typed array elements from this
324 // object.
325 if (pobj->is<TypedArrayObject>()) {
326 size_t len = pobj->as<TypedArrayObject>().length().valueOr(0);
327
328 // Fail early if the typed array is enormous, because this will be very
329 // slow and will likely report OOM. This also means we don't need to
330 // handle indices greater than PropertyKey::IntMax in the loop below.
331 static_assert(PropertyKey::IntMax == INT32_MAX);
332 if (len > INT32_MAX) {
333 ReportOutOfMemory(cx);
334 return false;
335 }
336
337 for (uint32_t i = 0; i < len; i++) {
338 if (!enumerate<CheckForDuplicates>(cx, PropertyKey::Int(i),
339 /* enumerable = */ true)) {
340 return false;
341 }
342 }
343 }
344
345 // The code below enumerates shape properties (including sparse elements) so
346 // if we can ignore those we're done.
347 if (!iterShapeProperties) {
348 return true;
349 }
350
351 // Collect any sparse elements from this object.
352 bool isIndexed = pobj->isIndexed();
353 if (isIndexed) {
354 // If the dense elements didn't have holes, we don't need to include
355 // them in the sort.
356 if (!hasHoles) {
357 firstElemIndex = props_.length();
358 }
359
360 for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
361 jsid id = iter->key();
362 uint32_t dummy;
363 if (IdIsIndex(id, &dummy)) {
364 if (!enumerate<CheckForDuplicates>(cx, id, iter->enumerable())) {
365 return false;
366 }
367 }
368 }
369
370 MOZ_ASSERT(firstElemIndex <= props_.length());
371
372 jsid* ids = props_.begin() + firstElemIndex;
373 size_t n = props_.length() - firstElemIndex;
374
375 RootedIdVector tmp(cx);
376 if (!tmp.resize(n)) {
377 return false;
378 }
379 PodCopy(tmp.begin(), ids, n);
380
381 if (!MergeSort(ids, n, tmp.begin(), SortComparatorIntegerIds)) {
382 return false;
383 }
384 }
385
386 size_t initialLength = props_.length();
387
388 /* Collect all unique property names from this object's shape. */
389 bool symbolsFound = false;
390 for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
391 jsid id = iter->key();
392
393 if (id.isSymbol()) {
394 symbolsFound = true;
395 continue;
396 }
397
398 uint32_t dummy;
399 if (isIndexed && IdIsIndex(id, &dummy)) {
400 continue;
401 }
402
403 PropertyIndex index = iter->isDataProperty() && iter->writable()
404 ? PropertyIndex::ForSlot(pobj, iter->slot())
405 : PropertyIndex::Invalid();
406 if (!enumerate<CheckForDuplicates>(cx, id, iter->enumerable(), index)) {
407 return false;
408 }
409 }
410 reversePropsAndIndicesAfter(initialLength);
411
412 enumerateSymbols = symbolsFound && (flags_ & JSITER_SYMBOLS);
413 }
414
415 if (enumerateSymbols) {
416 MOZ_ASSERT(iterShapeProperties);
417 MOZ_ASSERT(!allocatingIndices());
418
419 // Do a second pass to collect symbols. The spec requires that all symbols
420 // appear after all strings in [[OwnPropertyKeys]] for ordinary objects:
421 // https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
422 size_t initialLength = props_.length();
423 for (ShapePropertyIter<NoGC> iter(pobj->shape()); !iter.done(); iter++) {
424 jsid id = iter->key();
425 if (id.isSymbol()) {
426 if (!enumerate<CheckForDuplicates>(cx, id, iter->enumerable())) {
427 return false;
428 }
429 }
430 }
431 reversePropsAndIndicesAfter(initialLength);
432 }
433
434 return true;
435 }
436
437 template <bool CheckForDuplicates>
438 bool PropertyEnumerator::enumerateProxyProperties(JSContext* cx) {
439 MOZ_ASSERT(obj_->is<ProxyObject>());
440
441 RootedIdVector proxyProps(cx);
442
443 if (flags_ & JSITER_HIDDEN || flags_ & JSITER_SYMBOLS) {
444 // This gets all property keys, both strings and symbols. The call to
445 // enumerate in the loop below will filter out unwanted keys, per the
446 // flags.
447 if (!Proxy::ownPropertyKeys(cx, obj_, &proxyProps)) {
448 return false;
449 }
450
451 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
452 for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
453 bool enumerable = false;
454
455 // We need to filter, if the caller just wants enumerable symbols.
456 if (!(flags_ & JSITER_HIDDEN)) {
457 if (!Proxy::getOwnPropertyDescriptor(cx, obj_, proxyProps[n], &desc)) {
458 return false;
459 }
460 enumerable = desc.isSome() && desc->enumerable();
461 }
462
463 if (!enumerate<CheckForDuplicates>(cx, proxyProps[n], enumerable)) {
464 return false;
465 }
466 }
467
468 return true;
469 }
470
471 // Returns enumerable property names (no symbols).
472 if (!Proxy::getOwnEnumerablePropertyKeys(cx, obj_, &proxyProps)) {
473 return false;
474 }
475
476 for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
477 if (!enumerate<CheckForDuplicates>(cx, proxyProps[n], true)) {
478 return false;
479 }
480 }
481
482 return true;
483 }
484
485 #ifdef DEBUG
486
487 struct SortComparatorIds {
488 JSContext* const cx;
489
490 explicit SortComparatorIds(JSContext* cx) : cx(cx) {}
491
492 bool operator()(jsid aArg, jsid bArg, bool* lessOrEqualp) {
493 RootedId a(cx, aArg);
494 RootedId b(cx, bArg);
495
496 // Pick an arbitrary order on jsids that is as stable as possible
497 // across executions.
498 if (a == b) {
499 *lessOrEqualp = true;
500 return true;
501 }
502
503 enum class KeyType { Void, Int, String, Symbol };
504
505 auto keyType = [](PropertyKey key) {
506 if (key.isString()) {
507 return KeyType::String;
508 }
509 if (key.isInt()) {
510 return KeyType::Int;
511 }
512 if (key.isSymbol()) {
513 return KeyType::Symbol;
514 }
515 MOZ_ASSERT(key.isVoid());
516 return KeyType::Void;
517 };
518
519 if (keyType(a) != keyType(b)) {
520 *lessOrEqualp = (keyType(a) <= keyType(b));
521 return true;
522 }
523
524 if (a.isInt()) {
525 *lessOrEqualp = (a.toInt() <= b.toInt());
526 return true;
527 }
528
529 RootedString astr(cx), bstr(cx);
530 if (a.isSymbol()) {
531 MOZ_ASSERT(b.isSymbol());
532 JS::SymbolCode ca = a.toSymbol()->code();
533 JS::SymbolCode cb = b.toSymbol()->code();
534 if (ca != cb) {
535 *lessOrEqualp = uint32_t(ca) <= uint32_t(cb);
536 return true;
537 }
538 MOZ_ASSERT(ca == JS::SymbolCode::PrivateNameSymbol ||
539 ca == JS::SymbolCode::InSymbolRegistry ||
540 ca == JS::SymbolCode::UniqueSymbol);
541 astr = a.toSymbol()->description();
542 bstr = b.toSymbol()->description();
543 if (!astr || !bstr) {
544 *lessOrEqualp = !astr;
545 return true;
546 }
547
548 // Fall through to string comparison on the descriptions. The sort
549 // order is nondeterministic if two different unique symbols have
550 // the same description.
551 } else {
552 astr = IdToString(cx, a);
553 if (!astr) {
554 return false;
555 }
556 bstr = IdToString(cx, b);
557 if (!bstr) {
558 return false;
559 }
560 }
561
562 int32_t result;
563 if (!CompareStrings(cx, astr, bstr, &result)) {
564 return false;
565 }
566
567 *lessOrEqualp = (result <= 0);
568 return true;
569 }
570 };
571
572 #endif /* DEBUG */
573
574 static void AssertNoEnumerableProperties(NativeObject* obj) {
575 #ifdef DEBUG
576 // Verify the object has no enumerable properties if the HasEnumerable
577 // ObjectFlag is not set.
578
579 MOZ_ASSERT(!obj->hasEnumerableProperty());
580
581 static constexpr size_t MaxPropsToCheck = 5;
582
583 size_t count = 0;
584 for (ShapePropertyIter<NoGC> iter(obj->shape()); !iter.done(); iter++) {
585 MOZ_ASSERT(!iter->enumerable());
586 if (++count > MaxPropsToCheck) {
587 break;
588 }
589 }
590 #endif // DEBUG
591 }
592
593 static bool ProtoMayHaveEnumerableProperties(JSObject* obj) {
594 if (!obj->is<NativeObject>()) {
595 return true;
596 }
597
598 JSObject* proto = obj->as<NativeObject>().staticPrototype();
599 while (proto) {
600 if (!proto->is<NativeObject>()) {
601 return true;
602 }
603 NativeObject* nproto = &proto->as<NativeObject>();
604 if (nproto->hasEnumerableProperty() ||
605 nproto->getDenseInitializedLength() > 0 ||
606 ClassCanHaveExtraEnumeratedProperties(nproto->getClass())) {
607 return true;
608 }
609 AssertNoEnumerableProperties(nproto);
610 proto = nproto->staticPrototype();
611 }
612
613 return false;
614 }
615
616 bool PropertyEnumerator::snapshot(JSContext* cx) {
617 // If we're only interested in enumerable properties and the proto chain has
618 // no enumerable properties (the common case), we can optimize this to ignore
619 // the proto chain. This also lets us take advantage of the no-duplicate-check
620 // optimization below.
621 if (!(flags_ & JSITER_HIDDEN) && !(flags_ & JSITER_OWNONLY) &&
622 !ProtoMayHaveEnumerableProperties(obj_)) {
623 flags_ |= JSITER_OWNONLY;
624 }
625
626 // Don't check for duplicates if we're only interested in own properties.
627 // This does the right thing for most objects: native objects don't have
628 // duplicate property ids and we allow the [[OwnPropertyKeys]] proxy trap to
629 // return duplicates.
630 //
631 // The only special case is when the object has a newEnumerate hook: it
632 // can return duplicate properties and we have to filter them. This is
633 // handled below.
634 bool checkForDuplicates = !(flags_ & JSITER_OWNONLY);
635
636 do {
637 if (obj_->getClass()->getNewEnumerate()) {
638 markIndicesUnsupported();
639
640 if (!enumerateExtraProperties(cx)) {
641 return false;
642 }
643
644 if (obj_->is<NativeObject>()) {
645 if (!enumerateNativeProperties(cx, /*checkForDuplicates*/ true)) {
646 return false;
647 }
648 }
649
650 } else if (obj_->is<NativeObject>()) {
651 // Give the object a chance to resolve all lazy properties
652 if (JSEnumerateOp enumerateOp = obj_->getClass()->getEnumerate()) {
653 markIndicesUnsupported();
654 if (!enumerateOp(cx, obj_.as<NativeObject>())) {
655 return false;
656 }
657 }
658 if (!enumerateNativeProperties(cx, checkForDuplicates)) {
659 return false;
660 }
661 } else if (obj_->is<ProxyObject>()) {
662 markIndicesUnsupported();
663 if (checkForDuplicates) {
664 if (!enumerateProxyProperties<true>(cx)) {
665 return false;
666 }
667 } else {
668 if (!enumerateProxyProperties<false>(cx)) {
669 return false;
670 }
671 }
672 } else {
673 MOZ_CRASH("non-native objects must have an enumerate op");
674 }
675
676 if (flags_ & JSITER_OWNONLY) {
677 break;
678 }
679
680 if (!GetPrototype(cx, obj_, &obj_)) {
681 return false;
682 }
683 enumeratingProtoChain_ = true;
684
685 // The [[Prototype]] chain might be cyclic.
686 if (!CheckForInterrupt(cx)) {
687 return false;
688 }
689 } while (obj_ != nullptr);
690
691 #ifdef DEBUG
692 if (js::SupportDifferentialTesting() && !supportsIndices()) {
693 /*
694 * In some cases the enumeration order for an object depends on the
695 * execution mode (interpreter vs. JIT), especially for native objects
696 * with a class enumerate hook (where resolving a property changes the
697 * resulting enumeration order). These aren't really bugs, but the
698 * differences can change the generated output and confuse correctness
699 * fuzzers, so we sort the ids if such a fuzzer is running.
700 *
701 * We don't do this in the general case because (a) doing so is slow,
702 * and (b) it also breaks the web, which expects enumeration order to
703 * follow the order in which properties are added, in certain cases.
704 * Since ECMA does not specify an enumeration order for objects, both
705 * behaviors are technically correct to do.
706 */
707
708 jsid* ids = props_.begin();
709 size_t n = props_.length();
710
711 RootedIdVector tmp(cx);
712 if (!tmp.resize(n)) {
713 return false;
714 }
715 PodCopy(tmp.begin(), ids, n);
716
717 if (!MergeSort(ids, n, tmp.begin(), SortComparatorIds(cx))) {
718 return false;
719 }
720 }
721 #endif
722
723 return true;
724 }
725
726 JS_PUBLIC_API bool js::GetPropertyKeys(JSContext* cx, HandleObject obj,
727 unsigned flags,
728 MutableHandleIdVector props) {
729 uint32_t validFlags =
730 flags & (JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS |
731 JSITER_SYMBOLSONLY | JSITER_PRIVATE);
732
733 PropertyEnumerator enumerator(cx, obj, validFlags, props);
734 return enumerator.snapshot(cx);
735 }
736
737 static inline void RegisterEnumerator(JSContext* cx, NativeIterator* ni) {
738 MOZ_ASSERT(ni->objectBeingIterated());
739
740 // Register non-escaping native enumerators (for-in) with the current
741 // context.
742 ni->link(cx->compartment()->enumeratorsAddr());
743
744 MOZ_ASSERT(!ni->isActive());
745 ni->markActive();
746 }
747
748 static PropertyIteratorObject* NewPropertyIteratorObject(JSContext* cx) {
749 const JSClass* clasp = &PropertyIteratorObject::class_;
750 Rooted<SharedShape*> shape(
751 cx,
752 SharedShape::getInitialShape(cx, clasp, cx->realm(), TaggedProto(nullptr),
753 ITERATOR_FINALIZE_KIND));
754 if (!shape) {
755 return nullptr;
756 }
757
758 auto* res = NativeObject::create<PropertyIteratorObject>(
759 cx, ITERATOR_FINALIZE_KIND, GetInitialHeap(GenericObject, clasp), shape);
760 if (!res) {
761 return nullptr;
762 }
763
764 // CodeGenerator::visitIteratorStartO assumes the iterator object is not
765 // inside the nursery when deciding whether a barrier is necessary.
766 MOZ_ASSERT(!js::gc::IsInsideNursery(res));
767 return res;
768 }
769
770 static inline size_t NumTrailingBytes(size_t propertyCount, size_t shapeCount,
771 bool hasIndices) {
772 static_assert(alignof(GCPtr<JSLinearString*>) <= alignof(NativeIterator));
773 static_assert(alignof(GCPtr<Shape*>) <= alignof(GCPtr<JSLinearString*>));
774 static_assert(alignof(PropertyIndex) <= alignof(GCPtr<Shape*>));
775 size_t result = propertyCount * sizeof(GCPtr<JSLinearString*>) +
776 shapeCount * sizeof(GCPtr<Shape*>);
777 if (hasIndices) {
778 result += propertyCount * sizeof(PropertyIndex);
779 }
780 return result;
781 }
782
783 static inline size_t AllocationSize(size_t propertyCount, size_t shapeCount,
784 bool hasIndices) {
785 return sizeof(NativeIterator) +
786 NumTrailingBytes(propertyCount, shapeCount, hasIndices);
787 }
788
789 static PropertyIteratorObject* CreatePropertyIterator(
790 JSContext* cx, Handle<JSObject*> objBeingIterated, HandleIdVector props,
791 bool supportsIndices, PropertyIndexVector* indices,
792 uint32_t cacheableProtoChainLength) {
793 MOZ_ASSERT_IF(indices, supportsIndices);
794 if (props.length() >= NativeIterator::PropCountLimit) {
795 ReportAllocationOverflow(cx);
796 return nullptr;
797 }
798
799 bool hasIndices = !!indices;
800
801 // If the iterator is cacheable, we store the shape of each object
802 // along the proto chain in the iterator. If the iterator is not
803 // cacheable, but has indices, then we store one shape (the shape of
804 // the object being iterated.)
805 uint32_t numShapes = cacheableProtoChainLength;
806 if (numShapes == 0 && hasIndices) {
807 numShapes = 1;
808 }
809
810 Rooted<PropertyIteratorObject*> propIter(cx, NewPropertyIteratorObject(cx));
811 if (!propIter) {
812 return nullptr;
813 }
814
815 void* mem = cx->pod_malloc_with_extra<NativeIterator, uint8_t>(
816 NumTrailingBytes(props.length(), numShapes, hasIndices));
817 if (!mem) {
818 return nullptr;
819 }
820
821 // This also registers |ni| with |propIter|.
822 bool hadError = false;
823 new (mem) NativeIterator(cx, propIter, objBeingIterated, props,
824 supportsIndices, indices, numShapes, &hadError);
825 if (hadError) {
826 return nullptr;
827 }
828
829 return propIter;
830 }
831
832 static HashNumber HashIteratorShape(Shape* shape) {
833 return DefaultHasher<Shape*>::hash(shape);
834 }
835
836 /**
837 * Initialize a fresh NativeIterator.
838 *
839 * This definition is a bit tricky: some parts of initializing are fallible, so
840 * as we initialize, we must carefully keep this in GC-safe state (see
841 * NativeIterator::trace).
842 */
843 NativeIterator::NativeIterator(JSContext* cx,
844 Handle<PropertyIteratorObject*> propIter,
845 Handle<JSObject*> objBeingIterated,
846 HandleIdVector props, bool supportsIndices,
847 PropertyIndexVector* indices, uint32_t numShapes,
848 bool* hadError)
849 : objectBeingIterated_(objBeingIterated),
850 iterObj_(propIter),
851 // NativeIterator initially acts (before full initialization) as if it
852 // contains no shapes...
853 shapesEnd_(shapesBegin()),
854 // ...and no properties.
855 propertyCursor_(
856 reinterpret_cast<GCPtr<JSLinearString*>*>(shapesBegin() + numShapes)),
857 propertiesEnd_(propertyCursor_),
858 shapesHash_(0),
859 flagsAndCount_(
860 initialFlagsAndCount(props.length())) // note: no Flags::Initialized
861 {
862 // If there are shapes, the object and all objects on its prototype chain must
863 // be native objects. See CanCompareIterableObjectToCache.
864 MOZ_ASSERT_IF(numShapes > 0,
865 objBeingIterated && objBeingIterated->is<NativeObject>());
866
867 MOZ_ASSERT(!*hadError);
868
869 bool hasActualIndices = !!indices;
870 MOZ_ASSERT_IF(hasActualIndices, indices->length() == props.length());
871
872 // NOTE: This must be done first thing: The caller can't free `this` on error
873 // because it has GCPtr fields whose barriers have already fired; the
874 // store buffer has pointers to them. Only the GC can free `this` (via
875 // PropertyIteratorObject::finalize).
876 propIter->initNativeIterator(this);
877
878 // The GC asserts on finalization that `this->allocationSize()` matches the
879 // `nbytes` passed to `AddCellMemory`. So once these lines run, we must make
880 // `this->allocationSize()` correct. That means infallibly initializing the
881 // shapes, and ensuring that indicesState_.allocated() is true if we've
882 // allocated space for indices. It's OK for the constructor to fail after
883 // that.
884 size_t nbytes = AllocationSize(props.length(), numShapes, hasActualIndices);
885 AddCellMemory(propIter, nbytes, MemoryUse::NativeIterator);
886 if (supportsIndices) {
887 if (hasActualIndices) {
888 // If the string allocation fails, indicesAllocated() must be true
889 // so that this->allocationSize() is correct. Set it to Disabled. It will
890 // be updated below.
891 setIndicesState(NativeIteratorIndices::Disabled);
892 } else {
893 // This object supports indices (ie it only has own enumerable
894 // properties), but we didn't allocate them because we haven't seen a
895 // consumer yet. We mark the iterator so that potential consumers know to
896 // request a fresh iterator with indices.
897 setIndicesState(NativeIteratorIndices::AvailableOnRequest);
898 }
899 }
900
901 if (numShapes > 0) {
902 // Construct shapes into the shapes array. Also compute the shapesHash,
903 // which incorporates Shape* addresses that could have changed during a GC
904 // triggered in (among other places) |IdToString| above.
905 JSObject* pobj = objBeingIterated;
906 HashNumber shapesHash = 0;
907 for (uint32_t i = 0; i < numShapes; i++) {
908 MOZ_ASSERT(pobj->is<NativeObject>());
909 Shape* shape = pobj->shape();
910 new (shapesEnd_) GCPtr<Shape*>(shape);
911 shapesEnd_++;
912 shapesHash = mozilla::AddToHash(shapesHash, HashIteratorShape(shape));
913 pobj = pobj->staticPrototype();
914 }
915 shapesHash_ = shapesHash;
916
917 // There are two cases in which we need to store shapes. If this
918 // iterator is cacheable, we store the shapes for the entire proto
919 // chain so we can check that the cached iterator is still valid
920 // (see MacroAssembler::maybeLoadIteratorFromShape). If this iterator
921 // has indices, then even if it isn't cacheable we need to store the
922 // shape of the iterated object itself (see IteratorHasIndicesAndBranch).
923 // In the former case, assert that we're storing the entire proto chain.
924 MOZ_ASSERT_IF(numShapes > 1, pobj == nullptr);
925 }
926 MOZ_ASSERT(static_cast<void*>(shapesEnd_) == propertyCursor_);
927
928 // Allocate any strings in the nursery until the first minor GC. After this
929 // point they will end up getting tenured anyway because they are reachable
930 // from |propIter| which will be tenured.
931 AutoSelectGCHeap gcHeap(cx);
932
933 size_t numProps = props.length();
934 for (size_t i = 0; i < numProps; i++) {
935 JSLinearString* str = IdToString(cx, props[i], gcHeap);
936 if (!str) {
937 *hadError = true;
938 return;
939 }
940 new (propertiesEnd_) GCPtr<JSLinearString*>(str);
941 propertiesEnd_++;
942 }
943
944 if (hasActualIndices) {
945 PropertyIndex* cursor = indicesBegin();
946 for (size_t i = 0; i < numProps; i++) {
947 *cursor++ = (*indices)[i];
948 }
949 MOZ_ASSERT(uintptr_t(cursor) == uintptr_t(this) + nbytes);
950 setIndicesState(NativeIteratorIndices::Valid);
951 }
952
953 markInitialized();
954
955 MOZ_ASSERT(!*hadError);
956 }
957
958 inline size_t NativeIterator::allocationSize() const {
959 size_t numShapes = shapesEnd() - shapesBegin();
960
961 return AllocationSize(initialPropertyCount(), numShapes, indicesAllocated());
962 }
963
964 /* static */
965 bool IteratorHashPolicy::match(PropertyIteratorObject* obj,
966 const Lookup& lookup) {
967 NativeIterator* ni = obj->getNativeIterator();
968 if (ni->shapesHash() != lookup.shapesHash ||
969 ni->shapeCount() != lookup.numShapes) {
970 return false;
971 }
972
973 return ArrayEqual(reinterpret_cast<Shape**>(ni->shapesBegin()), lookup.shapes,
974 ni->shapeCount());
975 }
976
977 static inline bool CanCompareIterableObjectToCache(JSObject* obj) {
978 if (obj->is<NativeObject>()) {
979 return obj->as<NativeObject>().getDenseInitializedLength() == 0;
980 }
981 return false;
982 }
983
984 static bool CanStoreInIteratorCache(JSObject* obj) {
985 do {
986 MOZ_ASSERT(obj->as<NativeObject>().getDenseInitializedLength() == 0);
987
988 // Typed arrays have indexed properties not captured by the Shape guard.
989 // Enumerate hooks may add extra properties.
990 if (MOZ_UNLIKELY(ClassCanHaveExtraEnumeratedProperties(obj->getClass()))) {
991 return false;
992 }
993
994 obj = obj->staticPrototype();
995 } while (obj);
996
997 return true;
998 }
999
1000 static MOZ_ALWAYS_INLINE PropertyIteratorObject* LookupInShapeIteratorCache(
1001 JSContext* cx, JSObject* obj, uint32_t* cacheableProtoChainLength) {
1002 if (!obj->shape()->cache().isIterator() ||
1003 !CanCompareIterableObjectToCache(obj)) {
1004 return nullptr;
1005 }
1006 PropertyIteratorObject* iterobj = obj->shape()->cache().toIterator();
1007 NativeIterator* ni = iterobj->getNativeIterator();
1008 MOZ_ASSERT(*ni->shapesBegin() == obj->shape());
1009 if (!ni->isReusable()) {
1010 return nullptr;
1011 }
1012
1013 // Verify shapes of proto chain.
1014 JSObject* pobj = obj;
1015 for (GCPtr<Shape*>* s = ni->shapesBegin() + 1; s != ni->shapesEnd(); s++) {
1016 Shape* shape = *s;
1017 pobj = pobj->staticPrototype();
1018 if (pobj->shape() != shape) {
1019 return nullptr;
1020 }
1021 if (!CanCompareIterableObjectToCache(pobj)) {
1022 return nullptr;
1023 }
1024 }
1025 MOZ_ASSERT(CanStoreInIteratorCache(obj));
1026 *cacheableProtoChainLength = ni->shapeCount();
1027 return iterobj;
1028 }
1029
1030 static MOZ_ALWAYS_INLINE PropertyIteratorObject* LookupInIteratorCache(
1031 JSContext* cx, JSObject* obj, uint32_t* cacheableProtoChainLength) {
1032 MOZ_ASSERT(*cacheableProtoChainLength == 0);
1033
1034 if (PropertyIteratorObject* shapeCached =
1035 LookupInShapeIteratorCache(cx, obj, cacheableProtoChainLength)) {
1036 return shapeCached;
1037 }
1038
1039 Vector<Shape*, 8> shapes(cx);
1040 HashNumber shapesHash = 0;
1041 JSObject* pobj = obj;
1042 do {
1043 if (!CanCompareIterableObjectToCache(pobj)) {
1044 return nullptr;
1045 }
1046
1047 MOZ_ASSERT(pobj->is<NativeObject>());
1048 Shape* shape = pobj->shape();
1049 shapesHash = mozilla::AddToHash(shapesHash, HashIteratorShape(shape));
1050
1051 if (MOZ_UNLIKELY(!shapes.append(shape))) {
1052 cx->recoverFromOutOfMemory();
1053 return nullptr;
1054 }
1055
1056 pobj = pobj->staticPrototype();
1057 } while (pobj);
1058
1059 MOZ_ASSERT(!shapes.empty());
1060 *cacheableProtoChainLength = shapes.length();
1061
1062 IteratorHashPolicy::Lookup lookup(shapes.begin(), shapes.length(),
1063 shapesHash);
1064 auto p = ObjectRealm::get(obj).iteratorCache.lookup(lookup);
1065 if (!p) {
1066 return nullptr;
1067 }
1068
1069 PropertyIteratorObject* iterobj = *p;
1070 MOZ_ASSERT(iterobj->compartment() == cx->compartment());
1071
1072 NativeIterator* ni = iterobj->getNativeIterator();
1073 if (!ni->isReusable()) {
1074 return nullptr;
1075 }
1076
1077 return iterobj;
1078 }
1079
1080 [[nodiscard]] static bool StoreInIteratorCache(
1081 JSContext* cx, JSObject* obj, PropertyIteratorObject* iterobj) {
1082 MOZ_ASSERT(CanStoreInIteratorCache(obj));
1083
1084 NativeIterator* ni = iterobj->getNativeIterator();
1085 MOZ_ASSERT(ni->shapeCount() > 0);
1086
1087 obj->shape()->maybeCacheIterator(cx, iterobj);
1088
1089 IteratorHashPolicy::Lookup lookup(
1090 reinterpret_cast<Shape**>(ni->shapesBegin()), ni->shapeCount(),
1091 ni->shapesHash());
1092
1093 ObjectRealm::IteratorCache& cache = ObjectRealm::get(obj).iteratorCache;
1094 bool ok;
1095 auto p = cache.lookupForAdd(lookup);
1096 if (MOZ_LIKELY(!p)) {
1097 ok = cache.add(p, iterobj);
1098 } else {
1099 // If we weren't able to use an existing cached iterator, just
1100 // replace it.
1101 cache.remove(p);
1102 ok = cache.relookupOrAdd(p, lookup, iterobj);
1103 }
1104 if (!ok) {
1105 ReportOutOfMemory(cx);
1106 return false;
1107 }
1108
1109 return true;
1110 }
1111
1112 bool js::EnumerateProperties(JSContext* cx, HandleObject obj,
1113 MutableHandleIdVector props) {
1114 MOZ_ASSERT(props.empty());
1115
1116 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
1117 return Proxy::enumerate(cx, obj, props);
1118 }
1119
1120 uint32_t flags = 0;
1121 PropertyEnumerator enumerator(cx, obj, flags, props);
1122 return enumerator.snapshot(cx);
1123 }
1124
1125 #ifdef DEBUG
1126 static bool IndicesAreValid(NativeObject* obj, NativeIterator* ni) {
1127 MOZ_ASSERT(ni->hasValidIndices());
1128 size_t numDenseElements = obj->getDenseInitializedLength();
1129 size_t numFixedSlots = obj->numFixedSlots();
1130 const Value* elements = obj->getDenseElements();
1131
1132 GCPtr<JSLinearString*>* keys = ni->propertiesBegin();
1133 PropertyIndex* indices = ni->indicesBegin();
1134
1135 for (uint32_t i = 0; i < ni->numKeys(); i++) {
1136 PropertyIndex index = indices[i];
1137 switch (index.kind()) {
1138 case PropertyIndex::Kind::Element:
1139 // Verify that the dense element exists and is not a hole.
1140 if (index.index() >= numDenseElements ||
1141 elements[index.index()].isMagic(JS_ELEMENTS_HOLE)) {
1142 return false;
1143 }
1144 break;
1145 case PropertyIndex::Kind::FixedSlot: {
1146 // Verify that the slot exists and is an enumerable data property with
1147 // the expected key.
1148 Maybe<PropertyInfo> prop =
1149 obj->lookupPure(AtomToId(&keys[i]->asAtom()));
1150 if (!prop.isSome() || !prop->hasSlot() || !prop->enumerable() ||
1151 !prop->isDataProperty() || prop->slot() != index.index()) {
1152 return false;
1153 }
1154 break;
1155 }
1156 case PropertyIndex::Kind::DynamicSlot: {
1157 // Verify that the slot exists and is an enumerable data property with
1158 // the expected key.
1159 Maybe<PropertyInfo> prop =
1160 obj->lookupPure(AtomToId(&keys[i]->asAtom()));
1161 if (!prop.isSome() || !prop->hasSlot() || !prop->enumerable() ||
1162 !prop->isDataProperty() ||
1163 prop->slot() - numFixedSlots != index.index()) {
1164 return false;
1165 }
1166 break;
1167 }
1168 case PropertyIndex::Kind::Invalid:
1169 return false;
1170 }
1171 }
1172 return true;
1173 }
1174 #endif
1175
1176 template <bool WantIndices>
1177 static PropertyIteratorObject* GetIteratorImpl(JSContext* cx,
1178 HandleObject obj) {
1179 MOZ_ASSERT(!obj->is<PropertyIteratorObject>());
1180 MOZ_ASSERT(cx->compartment() == obj->compartment(),
1181 "We may end up allocating shapes in the wrong zone!");
1182
1183 uint32_t cacheableProtoChainLength = 0;
1184 if (PropertyIteratorObject* iterobj =
1185 LookupInIteratorCache(cx, obj, &cacheableProtoChainLength)) {
1186 NativeIterator* ni = iterobj->getNativeIterator();
1187 bool recreateWithIndices = WantIndices && ni->indicesAvailableOnRequest();
1188 if (!recreateWithIndices) {
1189 MOZ_ASSERT_IF(WantIndices && ni->hasValidIndices(),
1190 IndicesAreValid(&obj->as<NativeObject>(), ni));
1191 ni->initObjectBeingIterated(*obj);
1192 RegisterEnumerator(cx, ni);
1193 return iterobj;
1194 }
1195 }
1196
1197 if (cacheableProtoChainLength > 0 && !CanStoreInIteratorCache(obj)) {
1198 cacheableProtoChainLength = 0;
1199 }
1200
1201 RootedIdVector keys(cx);
1202 PropertyIndexVector indices(cx);
1203 bool supportsIndices = false;
1204
1205 if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
1206 if (!Proxy::enumerate(cx, obj, &keys)) {
1207 return nullptr;
1208 }
1209 } else {
1210 uint32_t flags = 0;
1211 PropertyEnumerator enumerator(cx, obj, flags, &keys, &indices);
1212 if (!enumerator.snapshot(cx)) {
1213 return nullptr;
1214 }
1215 supportsIndices = enumerator.supportsIndices();
1216 MOZ_ASSERT_IF(WantIndices && supportsIndices,
1217 keys.length() == indices.length());
1218 }
1219
1220 // If the object has dense elements, mark the dense elements as
1221 // maybe-in-iteration.
1222 //
1223 // The iterator is a snapshot so if indexed properties are added after this
1224 // point we don't need to do anything. However, the object might have sparse
1225 // elements now that can be densified later. To account for this, we set the
1226 // maybe-in-iteration flag also in NativeObject::maybeDensifySparseElements.
1227 //
1228 // In debug builds, AssertDenseElementsNotIterated is used to check the flag
1229 // is set correctly.
1230 if (obj->is<NativeObject>() &&
1231 obj->as<NativeObject>().getDenseInitializedLength() > 0) {
1232 obj->as<NativeObject>().markDenseElementsMaybeInIteration();
1233 }
1234
1235 PropertyIndexVector* indicesPtr =
1236 WantIndices && supportsIndices ? &indices : nullptr;
1237 PropertyIteratorObject* iterobj = CreatePropertyIterator(
1238 cx, obj, keys, supportsIndices, indicesPtr, cacheableProtoChainLength);
1239 if (!iterobj) {
1240 return nullptr;
1241 }
1242 RegisterEnumerator(cx, iterobj->getNativeIterator());
1243
1244 cx->check(iterobj);
1245 MOZ_ASSERT_IF(
1246 WantIndices && supportsIndices,
1247 IndicesAreValid(&obj->as<NativeObject>(), iterobj->getNativeIterator()));
1248
1249 #ifdef DEBUG
1250 if (obj->is<NativeObject>()) {
1251 if (PrototypeMayHaveIndexedProperties(&obj->as<NativeObject>())) {
1252 iterobj->getNativeIterator()->setMaybeHasIndexedPropertiesFromProto();
1253 }
1254 }
1255 #endif
1256
1257 // Cache the iterator object.
1258 if (cacheableProtoChainLength > 0) {
1259 if (!StoreInIteratorCache(cx, obj, iterobj)) {
1260 return nullptr;
1261 }
1262 }
1263
1264 return iterobj;
1265 }
1266
1267 PropertyIteratorObject* js::GetIterator(JSContext* cx, HandleObject obj) {
1268 return GetIteratorImpl<false>(cx, obj);
1269 }
1270
1271 PropertyIteratorObject* js::GetIteratorWithIndices(JSContext* cx,
1272 HandleObject obj) {
1273 return GetIteratorImpl<true>(cx, obj);
1274 }
1275
1276 PropertyIteratorObject* js::LookupInIteratorCache(JSContext* cx,
1277 HandleObject obj) {
1278 uint32_t dummy = 0;
1279 return LookupInIteratorCache(cx, obj, &dummy);
1280 }
1281
1282 PropertyIteratorObject* js::LookupInShapeIteratorCache(JSContext* cx,
1283 HandleObject obj) {
1284 uint32_t dummy = 0;
1285 return LookupInShapeIteratorCache(cx, obj, &dummy);
1286 }
1287
1288 // ES 2017 draft 7.4.7.
1289 PlainObject* js::CreateIterResultObject(JSContext* cx, HandleValue value,
1290 bool done) {
1291 // Step 1 (implicit).
1292
1293 // Step 2.
1294 Rooted<PlainObject*> templateObject(
1295 cx, GlobalObject::getOrCreateIterResultTemplateObject(cx));
1296 if (!templateObject) {
1297 return nullptr;
1298 }
1299
1300 PlainObject* resultObj = PlainObject::createWithTemplate(cx, templateObject);
1301 if (!resultObj) {
1302 return nullptr;
1303 }
1304
1305 // Step 3.
1306 resultObj->setSlot(GlobalObject::IterResultObjectValueSlot, value);
1307
1308 // Step 4.
1309 resultObj->setSlot(GlobalObject::IterResultObjectDoneSlot,
1310 done ? TrueHandleValue : FalseHandleValue);
1311
1312 // Step 5.
1313 return resultObj;
1314 }
1315
1316 PlainObject* GlobalObject::getOrCreateIterResultTemplateObject(JSContext* cx) {
1317 GCPtr<PlainObject*>& obj = cx->global()->data().iterResultTemplate;
1318 if (obj) {
1319 return obj;
1320 }
1321
1322 PlainObject* templateObj =
1323 createIterResultTemplateObject(cx, WithObjectPrototype::Yes);
1324 obj.init(templateObj);
1325 return obj;
1326 }
1327
1328 /* static */
1329 PlainObject* GlobalObject::getOrCreateIterResultWithoutPrototypeTemplateObject(
1330 JSContext* cx) {
1331 GCPtr<PlainObject*>& obj =
1332 cx->global()->data().iterResultWithoutPrototypeTemplate;
1333 if (obj) {
1334 return obj;
1335 }
1336
1337 PlainObject* templateObj =
1338 createIterResultTemplateObject(cx, WithObjectPrototype::No);
1339 obj.init(templateObj);
1340 return obj;
1341 }
1342
1343 /* static */
1344 PlainObject* GlobalObject::createIterResultTemplateObject(
1345 JSContext* cx, WithObjectPrototype withProto) {
1346 // Create template plain object
1347 Rooted<PlainObject*> templateObject(
1348 cx, withProto == WithObjectPrototype::Yes
1349 ? NewPlainObject(cx, TenuredObject)
1350 : NewPlainObjectWithProto(cx, nullptr));
1351 if (!templateObject) {
1352 return nullptr;
1353 }
1354
1355 // Set dummy `value` property
1356 if (!NativeDefineDataProperty(cx, templateObject, cx->names().value,
1357 UndefinedHandleValue, JSPROP_ENUMERATE)) {
1358 return nullptr;
1359 }
1360
1361 // Set dummy `done` property
1362 if (!NativeDefineDataProperty(cx, templateObject, cx->names().done,
1363 TrueHandleValue, JSPROP_ENUMERATE)) {
1364 return nullptr;
1365 }
1366
1367 #ifdef DEBUG
1368 // Make sure that the properties are in the right slots.
1369 ShapePropertyIter<NoGC> iter(templateObject->shape());
1370 MOZ_ASSERT(iter->slot() == GlobalObject::IterResultObjectDoneSlot &&
1371 iter->key() == NameToId(cx->names().done));
1372 iter++;
1373 MOZ_ASSERT(iter->slot() == GlobalObject::IterResultObjectValueSlot &&
1374 iter->key() == NameToId(cx->names().value));
1375 #endif
1376
1377 return templateObject;
1378 }
1379
1380 /*** Iterator objects *******************************************************/
1381
1382 size_t PropertyIteratorObject::sizeOfMisc(
1383 mozilla::MallocSizeOf mallocSizeOf) const {
1384 return mallocSizeOf(getNativeIterator());
1385 }
1386
1387 void PropertyIteratorObject::trace(JSTracer* trc, JSObject* obj) {
1388 if (NativeIterator* ni =
1389 obj->as<PropertyIteratorObject>().getNativeIterator()) {
1390 ni->trace(trc);
1391 }
1392 }
1393
1394 void PropertyIteratorObject::finalize(JS::GCContext* gcx, JSObject* obj) {
1395 if (NativeIterator* ni =
1396 obj->as<PropertyIteratorObject>().getNativeIterator()) {
1397 gcx->free_(obj, ni, ni->allocationSize(), MemoryUse::NativeIterator);
1398 }
1399 }
1400
1401 const JSClassOps PropertyIteratorObject::classOps_ = {
1402 nullptr, // addProperty
1403 nullptr, // delProperty
1404 nullptr, // enumerate
1405 nullptr, // newEnumerate
1406 nullptr, // resolve
1407 nullptr, // mayResolve
1408 finalize, // finalize
1409 nullptr, // call
1410 nullptr, // construct
1411 trace, // trace
1412 };
1413
1414 const JSClass PropertyIteratorObject::class_ = {
1415 "Iterator",
1416 JSCLASS_HAS_RESERVED_SLOTS(SlotCount) | JSCLASS_BACKGROUND_FINALIZE,
1417 &PropertyIteratorObject::classOps_,
1418 };
1419
1420 static const JSClass ArrayIteratorPrototypeClass = {
1421 "Array Iterator",
1422 0,
1423 };
1424
1425 enum {
1426 ArrayIteratorSlotIteratedObject,
1427 ArrayIteratorSlotNextIndex,
1428 ArrayIteratorSlotItemKind,
1429 ArrayIteratorSlotCount
1430 };
1431 // Slot numbers must match constants used in self-hosted code.
1432 static_assert(ArrayIteratorSlotIteratedObject == ITERATOR_SLOT_TARGET);
1433 static_assert(ArrayIteratorSlotNextIndex == ITERATOR_SLOT_NEXT_INDEX);
1434 static_assert(ArrayIteratorSlotItemKind == ARRAY_ITERATOR_SLOT_ITEM_KIND);
1435
1436 const JSClass ArrayIteratorObject::class_ = {
1437 "Array Iterator",
1438 JSCLASS_HAS_RESERVED_SLOTS(ArrayIteratorSlotCount),
1439 };
1440
1441 ArrayIteratorObject* js::NewArrayIteratorTemplate(JSContext* cx) {
1442 RootedObject proto(
1443 cx, GlobalObject::getOrCreateArrayIteratorPrototype(cx, cx->global()));
1444 if (!proto) {
1445 return nullptr;
1446 }
1447
1448 return NewTenuredObjectWithGivenProto<ArrayIteratorObject>(cx, proto);
1449 }
1450
1451 ArrayIteratorObject* js::NewArrayIterator(JSContext* cx) {
1452 RootedObject proto(
1453 cx, GlobalObject::getOrCreateArrayIteratorPrototype(cx, cx->global()));
1454 if (!proto) {
1455 return nullptr;
1456 }
1457
1458 return NewObjectWithGivenProto<ArrayIteratorObject>(cx, proto);
1459 }
1460
1461 static const JSFunctionSpec array_iterator_methods[] = {
1462 JS_SELF_HOSTED_FN("next", "ArrayIteratorNext", 0, 0),
1463 JS_FS_END,
1464 };
1465
1466 static const JSClass StringIteratorPrototypeClass = {
1467 "String Iterator",
1468 0,
1469 };
1470
1471 enum {
1472 StringIteratorSlotIteratedObject,
1473 StringIteratorSlotNextIndex,
1474 StringIteratorSlotCount
1475 };
1476 // Slot numbers must match constants used in self-hosted code.
1477 static_assert(StringIteratorSlotIteratedObject == ITERATOR_SLOT_TARGET);
1478 static_assert(StringIteratorSlotNextIndex == ITERATOR_SLOT_NEXT_INDEX);
1479
1480 const JSClass StringIteratorObject::class_ = {
1481 "String Iterator",
1482 JSCLASS_HAS_RESERVED_SLOTS(StringIteratorSlotCount),
1483 };
1484
1485 static const JSFunctionSpec string_iterator_methods[] = {
1486 JS_SELF_HOSTED_FN("next", "StringIteratorNext", 0, 0),
1487 JS_FS_END,
1488 };
1489
1490 StringIteratorObject* js::NewStringIteratorTemplate(JSContext* cx) {
1491 RootedObject proto(
1492 cx, GlobalObject::getOrCreateStringIteratorPrototype(cx, cx->global()));
1493 if (!proto) {
1494 return nullptr;
1495 }
1496
1497 return NewTenuredObjectWithGivenProto<StringIteratorObject>(cx, proto);
1498 }
1499
1500 StringIteratorObject* js::NewStringIterator(JSContext* cx) {
1501 RootedObject proto(
1502 cx, GlobalObject::getOrCreateStringIteratorPrototype(cx, cx->global()));
1503 if (!proto) {
1504 return nullptr;
1505 }
1506
1507 return NewObjectWithGivenProto<StringIteratorObject>(cx, proto);
1508 }
1509
1510 static const JSClass RegExpStringIteratorPrototypeClass = {
1511 "RegExp String Iterator",
1512 0,
1513 };
1514
1515 enum {
1516 // The regular expression used for iteration. May hold the original RegExp
1517 // object when it is reused instead of a new RegExp object.
1518 RegExpStringIteratorSlotRegExp,
1519
1520 // The String value being iterated upon.
1521 RegExpStringIteratorSlotString,
1522
1523 // The source string of the original RegExp object. Used to validate we can
1524 // reuse the original RegExp object for matching.
1525 RegExpStringIteratorSlotSource,
1526
1527 // The flags of the original RegExp object.
1528 RegExpStringIteratorSlotFlags,
1529
1530 // When non-negative, this slot holds the current lastIndex position when
1531 // reusing the original RegExp object for matching. When set to |-1|, the
1532 // iterator has finished. When set to any other negative value, the
1533 // iterator is not yet exhausted and we're not on the fast path and we're
1534 // not reusing the input RegExp object.
1535 RegExpStringIteratorSlotLastIndex,
1536
1537 RegExpStringIteratorSlotCount
1538 };
1539
1540 static_assert(RegExpStringIteratorSlotRegExp ==
1541 REGEXP_STRING_ITERATOR_REGEXP_SLOT,
1542 "RegExpStringIteratorSlotRegExp must match self-hosting define "
1543 "for regexp slot.");
1544 static_assert(RegExpStringIteratorSlotString ==
1545 REGEXP_STRING_ITERATOR_STRING_SLOT,
1546 "RegExpStringIteratorSlotString must match self-hosting define "
1547 "for string slot.");
1548 static_assert(RegExpStringIteratorSlotSource ==
1549 REGEXP_STRING_ITERATOR_SOURCE_SLOT,
1550 "RegExpStringIteratorSlotString must match self-hosting define "
1551 "for source slot.");
1552 static_assert(RegExpStringIteratorSlotFlags ==
1553 REGEXP_STRING_ITERATOR_FLAGS_SLOT,
1554 "RegExpStringIteratorSlotFlags must match self-hosting define "
1555 "for flags slot.");
1556 static_assert(RegExpStringIteratorSlotLastIndex ==
1557 REGEXP_STRING_ITERATOR_LASTINDEX_SLOT,
1558 "RegExpStringIteratorSlotLastIndex must match self-hosting "
1559 "define for lastIndex slot.");
1560
1561 const JSClass RegExpStringIteratorObject::class_ = {
1562 "RegExp String Iterator",
1563 JSCLASS_HAS_RESERVED_SLOTS(RegExpStringIteratorSlotCount),
1564 };
1565
1566 static const JSFunctionSpec regexp_string_iterator_methods[] = {
1567 JS_SELF_HOSTED_FN("next", "RegExpStringIteratorNext", 0, 0),
1568
1569 JS_FS_END,
1570 };
1571
1572 RegExpStringIteratorObject* js::NewRegExpStringIteratorTemplate(JSContext* cx) {
1573 RootedObject proto(cx, GlobalObject::getOrCreateRegExpStringIteratorPrototype(
1574 cx, cx->global()));
1575 if (!proto) {
1576 return nullptr;
1577 }
1578
1579 return NewTenuredObjectWithGivenProto<RegExpStringIteratorObject>(cx, proto);
1580 }
1581
1582 RegExpStringIteratorObject* js::NewRegExpStringIterator(JSContext* cx) {
1583 RootedObject proto(cx, GlobalObject::getOrCreateRegExpStringIteratorPrototype(
1584 cx, cx->global()));
1585 if (!proto) {
1586 return nullptr;
1587 }
1588
1589 return NewObjectWithGivenProto<RegExpStringIteratorObject>(cx, proto);
1590 }
1591
1592 #ifdef NIGHTLY_BUILD
1593 static const JSClass IteratorRangePrototypeClass = {
1594 "Numeric Range Iterator",
1595 0,
1596 };
1597
1598 enum {
1599 IteratorRangeSlotStart,
1600 IteratorRangeSlotEnd,
1601 IteratorRangeSlotStep,
1602 IteratorRangeSlotInclusiveEnd,
1603 IteratorRangeSlotZero,
1604 IteratorRangeSlotOne,
1605 IteratorRangeSlotCurrentCount,
1606 IteratorRangeSlotCount
1607 };
1608
1609 // slot numbers must match constants used in self-hosted code
1610 static_assert(IteratorRangeSlotStart == ITERATOR_RANGE_SLOT_START);
1611 static_assert(IteratorRangeSlotEnd == ITERATOR_RANGE_SLOT_END);
1612 static_assert(IteratorRangeSlotStep == ITERATOR_RANGE_SLOT_STEP);
1613 static_assert(IteratorRangeSlotInclusiveEnd ==
1614 ITERATOR_RANGE_SLOT_INCLUSIVE_END);
1615 static_assert(IteratorRangeSlotZero == ITERATOR_RANGE_SLOT_ZERO);
1616 static_assert(IteratorRangeSlotOne == ITERATOR_RANGE_SLOT_ONE);
1617 static_assert(IteratorRangeSlotCurrentCount ==
1618 ITERATOR_RANGE_SLOT_CURRENT_COUNT);
1619
1620 static const JSFunctionSpec iterator_range_methods[] = {
1621 JS_SELF_HOSTED_FN("next", "IteratorRangeNext", 0, 0),
1622 JS_FS_END,
1623 };
1624
1625 IteratorRangeObject* js::NewIteratorRange(JSContext* cx) {
1626 RootedObject proto(
1627 cx, GlobalObject::getOrCreateIteratorRangePrototype(cx, cx->global()));
1628 if (!proto) {
1629 return nullptr;
1630 }
1631
1632 return NewObjectWithGivenProto<IteratorRangeObject>(cx, proto);
1633 }
1634 #endif
1635
1636 // static
1637 PropertyIteratorObject* GlobalObject::getOrCreateEmptyIterator(JSContext* cx) {
1638 if (!cx->global()->data().emptyIterator) {
1639 RootedIdVector props(cx); // Empty
1640 PropertyIteratorObject* iter =
1641 CreatePropertyIterator(cx, nullptr, props, false, nullptr, 0);
1642 if (!iter) {
1643 return nullptr;
1644 }
1645 iter->getNativeIterator()->markEmptyIteratorSingleton();
1646 cx->global()->data().emptyIterator.init(iter);
1647 }
1648 return cx->global()->data().emptyIterator;
1649 }
1650
1651 PropertyIteratorObject* js::ValueToIterator(JSContext* cx, HandleValue vp) {
1652 RootedObject obj(cx);
1653 if (vp.isObject()) {
1654 /* Common case. */
1655 obj = &vp.toObject();
1656 } else if (vp.isNullOrUndefined()) {
1657 /*
1658 * Enumerating over null and undefined gives an empty enumerator, so
1659 * that |for (var p in <null or undefined>) <loop>;| never executes
1660 * <loop>, per ES5 12.6.4.
1661 */
1662 return GlobalObject::getOrCreateEmptyIterator(cx);
1663 } else {
1664 obj = ToObject(cx, vp);
1665 if (!obj) {
1666 return nullptr;
1667 }
1668 }
1669
1670 return GetIterator(cx, obj);
1671 }
1672
1673 void js::CloseIterator(JSObject* obj) {
1674 if (!obj->is<PropertyIteratorObject>()) {
1675 return;
1676 }
1677
1678 // Remove iterator from the active list, which is a stack. The shared iterator
1679 // used for for-in with null/undefined is immutable and unlinked.
1680
1681 NativeIterator* ni = obj->as<PropertyIteratorObject>().getNativeIterator();
1682 if (ni->isEmptyIteratorSingleton()) {
1683 return;
1684 }
1685
1686 ni->unlink();
1687
1688 MOZ_ASSERT(ni->isActive());
1689 ni->markInactive();
1690
1691 ni->clearObjectBeingIterated();
1692
1693 // Reset the enumerator; it may still be in the cached iterators for
1694 // this thread and can be reused.
1695 ni->resetPropertyCursorForReuse();
1696 }
1697
1698 bool js::IteratorCloseForException(JSContext* cx, HandleObject obj) {
1699 MOZ_ASSERT(cx->isExceptionPending());
1700
1701 bool isClosingGenerator = cx->isClosingGenerator();
1702 JS::AutoSaveExceptionState savedExc(cx);
1703
1704 // Implements IteratorClose (ES 7.4.6) for exception unwinding. See
1705 // also the bytecode generated by BytecodeEmitter::emitIteratorClose.
1706
1707 // Step 3.
1708 //
1709 // Get the "return" method.
1710 RootedValue returnMethod(cx);
1711 if (!GetProperty(cx, obj, obj, cx->names().return_, &returnMethod)) {
1712 return false;
1713 }
1714
1715 // Step 4.
1716 //
1717 // Do nothing if "return" is null or undefined. Throw a TypeError if the
1718 // method is not IsCallable.
1719 if (returnMethod.isNullOrUndefined()) {
1720 return true;
1721 }
1722 if (!IsCallable(returnMethod)) {
1723 return ReportIsNotFunction(cx, returnMethod);
1724 }
1725
1726 // Step 5, 6, 8.
1727 //
1728 // Call "return" if it is not null or undefined.
1729 RootedValue rval(cx);
1730 bool ok = Call(cx, returnMethod, obj, &rval);
1731 if (isClosingGenerator) {
1732 // Closing an iterator is implemented as an exception, but in spec
1733 // terms it is a Completion value with [[Type]] return. In this case
1734 // we *do* care if the call threw and if it returned an object.
1735 if (!ok) {
1736 return false;
1737 }
1738 if (!rval.isObject()) {
1739 return ThrowCheckIsObject(cx, CheckIsObjectKind::IteratorReturn);
1740 }
1741 } else {
1742 // We don't care if the call threw or that it returned an Object, as
1743 // Step 6 says if IteratorClose is being called during a throw, the
1744 // original throw has primacy.
1745 savedExc.restore();
1746 }
1747
1748 return true;
1749 }
1750
1751 void js::UnwindIteratorForUncatchableException(JSObject* obj) {
1752 if (obj->is<PropertyIteratorObject>()) {
1753 NativeIterator* ni = obj->as<PropertyIteratorObject>().getNativeIterator();
1754 if (ni->isEmptyIteratorSingleton()) {
1755 return;
1756 }
1757 ni->unlink();
1758 }
1759 }
1760
1761 static bool SuppressDeletedProperty(JSContext* cx, NativeIterator* ni,
1762 HandleObject obj,
1763 Handle<JSLinearString*> str) {
1764 if (ni->objectBeingIterated() != obj) {
1765 return true;
1766 }
1767
1768 ni->disableIndices();
1769
1770 // Optimization for the following common case:
1771 //
1772 // for (var p in o) {
1773 // delete o[p];
1774 // }
1775 //
1776 // Note that usually both strings will be atoms so we only check for pointer
1777 // equality here.
1778 if (ni->previousPropertyWas(str)) {
1779 return true;
1780 }
1781
1782 while (true) {
1783 bool restart = false;
1784
1785 // Check whether id is still to come.
1786 GCPtr<JSLinearString*>* const cursor = ni->nextProperty();
1787 GCPtr<JSLinearString*>* const end = ni->propertiesEnd();
1788 for (GCPtr<JSLinearString*>* idp = cursor; idp < end; ++idp) {
1789 // Common case: both strings are atoms.
1790 if ((*idp)->isAtom() && str->isAtom()) {
1791 if (*idp != str) {
1792 continue;
1793 }
1794 } else {
1795 if (!EqualStrings(*idp, str)) {
1796 continue;
1797 }
1798 }
1799
1800 // Check whether another property along the prototype chain became
1801 // visible as a result of this deletion.
1802 if (obj->hasStaticPrototype()) {
1803 JSObject* proto = obj->staticPrototype();
1804 if (proto) {
1805 JSAtom* atom = AtomizeString(cx, str);
1806 if (!atom) {
1807 return false;
1808 }
1809 PropertyKey key = AtomToId(atom);
1810 NativeObject* holder = nullptr;
1811 PropertyResult prop;
1812 if (LookupPropertyPure(cx, proto, key, &holder, &prop) &&
1813 prop.isFound()) {
1814 JS::PropertyAttributes attrs = GetPropertyAttributes(holder, prop);
1815 if (attrs.enumerable()) {
1816 continue;
1817 }
1818 }
1819 }
1820 }
1821
1822 // If GetPropertyDescriptor above removed a property from ni, start
1823 // over.
1824 if (end != ni->propertiesEnd() || cursor != ni->nextProperty()) {
1825 restart = true;
1826 break;
1827 }
1828
1829 // No property along the prototype chain stepped in to take the
1830 // property's place, so go ahead and delete id from the list.
1831 // If it is the next property to be enumerated, just skip it.
1832 if (idp == cursor) {
1833 ni->incCursor();
1834 } else {
1835 for (GCPtr<JSLinearString*>* p = idp; p + 1 != end; p++) {
1836 *p = *(p + 1);
1837 }
1838
1839 ni->trimLastProperty();
1840 }
1841
1842 ni->markHasUnvisitedPropertyDeletion();
1843 return true;
1844 }
1845
1846 if (!restart) {
1847 return true;
1848 }
1849 }
1850 }
1851
1852 /*
1853 * Suppress enumeration of deleted properties. This function must be called
1854 * when a property is deleted and there might be active enumerators.
1855 *
1856 * We maintain a list of active non-escaping for-in enumerators. To suppress
1857 * a property, we check whether each active enumerator contains the (obj, id)
1858 * pair and has not yet enumerated |id|. If so, and |id| is the next property,
1859 * we simply advance the cursor. Otherwise, we delete |id| from the list.
1860 *
1861 * We do not suppress enumeration of a property deleted along an object's
1862 * prototype chain. Only direct deletions on the object are handled.
1863 */
1864 static bool SuppressDeletedPropertyHelper(JSContext* cx, HandleObject obj,
1865 Handle<JSLinearString*> str) {
1866 NativeIteratorListIter iter(obj->compartment()->enumeratorsAddr());
1867 while (!iter.done()) {
1868 NativeIterator* ni = iter.next();
1869 if (!SuppressDeletedProperty(cx, ni, obj, str)) {
1870 return false;
1871 }
1872 }
1873
1874 return true;
1875 }
1876
1877 bool js::SuppressDeletedProperty(JSContext* cx, HandleObject obj, jsid id) {
1878 if (MOZ_LIKELY(!obj->compartment()->objectMaybeInIteration(obj))) {
1879 return true;
1880 }
1881
1882 if (id.isSymbol()) {
1883 return true;
1884 }
1885
1886 Rooted<JSLinearString*> str(cx, IdToString(cx, id));
1887 if (!str) {
1888 return false;
1889 }
1890 return SuppressDeletedPropertyHelper(cx, obj, str);
1891 }
1892
1893 bool js::SuppressDeletedElement(JSContext* cx, HandleObject obj,
1894 uint32_t index) {
1895 if (MOZ_LIKELY(!obj->compartment()->objectMaybeInIteration(obj))) {
1896 return true;
1897 }
1898
1899 RootedId id(cx);
1900 if (!IndexToId(cx, index, &id)) {
1901 return false;
1902 }
1903
1904 Rooted<JSLinearString*> str(cx, IdToString(cx, id));
1905 if (!str) {
1906 return false;
1907 }
1908 return SuppressDeletedPropertyHelper(cx, obj, str);
1909 }
1910
1911 #ifdef DEBUG
1912 void js::AssertDenseElementsNotIterated(NativeObject* obj) {
1913 // Search for active iterators for |obj| and assert they don't contain any
1914 // property keys that are dense elements. This is used to check correctness
1915 // of the MAYBE_IN_ITERATION flag on ObjectElements.
1916 //
1917 // Ignore iterators that may contain indexed properties from objects on the
1918 // prototype chain, as that can result in false positives. See bug 1656744.
1919
1920 // Limit the number of properties we check to avoid slowing down debug builds
1921 // too much.
1922 static constexpr uint32_t MaxPropsToCheck = 10;
1923 uint32_t propsChecked = 0;
1924
1925 NativeIteratorListIter iter(obj->compartment()->enumeratorsAddr());
1926 while (!iter.done()) {
1927 NativeIterator* ni = iter.next();
1928 if (ni->objectBeingIterated() == obj &&
1929 !ni->maybeHasIndexedPropertiesFromProto()) {
1930 for (GCPtr<JSLinearString*>* idp = ni->nextProperty();
1931 idp < ni->propertiesEnd(); ++idp) {
1932 uint32_t index;
1933 if (idp->get()->isIndex(&index)) {
1934 MOZ_ASSERT(!obj->containsDenseElement(index));
1935 }
1936 if (++propsChecked > MaxPropsToCheck) {
1937 return;
1938 }
1939 }
1940 }
1941 }
1942 }
1943 #endif
1944
1945 static const JSFunctionSpec iterator_static_methods[] = {
1946 JS_SELF_HOSTED_FN("from", "IteratorFrom", 1, 0),
1947 #ifdef NIGHTLY_BUILD
1948 JS_SELF_HOSTED_FN("concat", "IteratorConcat", 0, 0),
1949 JS_SELF_HOSTED_FN("range", "IteratorRange", 3, 0),
1950 JS_SELF_HOSTED_FN("zip", "IteratorZip", 1, 0),
1951 JS_SELF_HOSTED_FN("zipKeyed", "IteratorZipKeyed", 1, 0),
1952 #endif
1953 JS_FS_END,
1954 };
1955
1956 // These methods are only attached to Iterator.prototype when the
1957 // Iterator Helpers feature is enabled.
1958 static const JSFunctionSpec iterator_methods[] = {
1959 JS_SELF_HOSTED_FN("map", "IteratorMap", 1, 0),
1960 JS_SELF_HOSTED_FN("filter", "IteratorFilter", 1, 0),
1961 JS_SELF_HOSTED_FN("take", "IteratorTake", 1, 0),
1962 JS_SELF_HOSTED_FN("drop", "IteratorDrop", 1, 0),
1963 JS_SELF_HOSTED_FN("flatMap", "IteratorFlatMap", 1, 0),
1964 JS_SELF_HOSTED_FN("reduce", "IteratorReduce", 1, 0),
1965 JS_SELF_HOSTED_FN("toArray", "IteratorToArray", 0, 0),
1966 JS_SELF_HOSTED_FN("forEach", "IteratorForEach", 1, 0),
1967 JS_SELF_HOSTED_FN("some", "IteratorSome", 1, 0),
1968 JS_SELF_HOSTED_FN("every", "IteratorEvery", 1, 0),
1969 JS_SELF_HOSTED_FN("find", "IteratorFind", 1, 0),
1970 JS_SELF_HOSTED_SYM_FN(iterator, "IteratorIdentity", 0, 0),
1971 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1972 JS_SELF_HOSTED_SYM_FN(dispose, "IteratorDispose", 0, 0),
1973 #endif
1974 JS_FS_END,
1975 };
1976
1977 // https://tc39.es/proposal-iterator-helpers/#sec-SetterThatIgnoresPrototypeProperties
1978 static bool SetterThatIgnoresPrototypeProperties(JSContext* cx,
1979 Handle<Value> thisv,
1980 Handle<PropertyKey> prop,
1981 Handle<Value> value) {
1982 // Step 1.
1983 Rooted<JSObject*> thisObj(cx,
1984 RequireObject(cx, JSMSG_OBJECT_REQUIRED, thisv));
1985 if (!thisObj) {
1986 return false;
1987 }
1988
1989 // Step 2.
1990 Rooted<JSObject*> home(
1991 cx, GlobalObject::getOrCreateIteratorPrototype(cx, cx->global()));
1992 if (!home) {
1993 return false;
1994 }
1995 if (thisObj == home) {
1996 UniqueChars propName =
1997 IdToPrintableUTF8(cx, prop, IdToPrintableBehavior::IdIsPropertyKey);
1998 if (!propName) {
1999 return false;
2000 }
2001
2002 // Step 2.b.
2003 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_READ_ONLY,
2004 propName.get());
2005 return false;
2006 }
2007
2008 // Step 3.
2009 Rooted<Maybe<PropertyDescriptor>> desc(cx);
2010 if (!GetOwnPropertyDescriptor(cx, thisObj, prop, &desc)) {
2011 return false;
2012 }
2013
2014 // Step 4.
2015 if (desc.isNothing()) {
2016 // Step 4.a.
2017 return DefineDataProperty(cx, thisObj, prop, value, JSPROP_ENUMERATE);
2018 }
2019
2020 // Step 5.
2021 return SetProperty(cx, thisObj, prop, value);
2022 }
2023
2024 // https://tc39.es/proposal-iterator-helpers/#sec-get-iteratorprototype-@@tostringtag
2025 static bool toStringTagGetter(JSContext* cx, unsigned argc, Value* vp) {
2026 CallArgs args = CallArgsFromVp(argc, vp);
2027
2028 // Step 1.
2029 args.rval().setString(cx->names().Iterator);
2030 return true;
2031 }
2032
2033 // https://tc39.es/proposal-iterator-helpers/#sec-set-iteratorprototype-@@tostringtag
2034 static bool toStringTagSetter(JSContext* cx, unsigned argc, Value* vp) {
2035 CallArgs args = CallArgsFromVp(argc, vp);
2036
2037 // Step 1.
2038 Rooted<PropertyKey> prop(
2039 cx, PropertyKey::Symbol(cx->wellKnownSymbols().toStringTag));
2040 if (!SetterThatIgnoresPrototypeProperties(cx, args.thisv(), prop,
2041 args.get(0))) {
2042 return false;
2043 }
2044
2045 // Step 2.
2046 args.rval().setUndefined();
2047 return true;
2048 }
2049
2050 // https://tc39.es/proposal-iterator-helpers/#sec-get-iteratorprototype-constructor
2051 static bool constructorGetter(JSContext* cx, unsigned argc, Value* vp) {
2052 CallArgs args = CallArgsFromVp(argc, vp);
2053
2054 // Step 1.
2055 Rooted<JSObject*> constructor(
2056 cx, GlobalObject::getOrCreateConstructor(cx, JSProto_Iterator));
2057 if (!constructor) {
2058 return false;
2059 }
2060 args.rval().setObject(*constructor);
2061 return true;
2062 }
2063
2064 // https://tc39.es/proposal-iterator-helpers/#sec-set-iteratorprototype-constructor
2065 static bool constructorSetter(JSContext* cx, unsigned argc, Value* vp) {
2066 CallArgs args = CallArgsFromVp(argc, vp);
2067
2068 // Step 1.
2069 Rooted<PropertyKey> prop(cx, NameToId(cx->names().constructor));
2070 if (!SetterThatIgnoresPrototypeProperties(cx, args.thisv(), prop,
2071 args.get(0))) {
2072 return false;
2073 }
2074
2075 // Step 2.
2076 args.rval().setUndefined();
2077 return true;
2078 }
2079
2080 static const JSPropertySpec iterator_properties[] = {
2081 // NOTE: Contrary to most other @@toStringTag properties, this property
2082 // has a special setter (and a getter).
2083 JS_SYM_GETSET(toStringTag, toStringTagGetter, toStringTagSetter, 0),
2084 JS_PS_END,
2085 };
2086
2087 /* static */
2088 template <GlobalObject::ProtoKind Kind, const JSClass* ProtoClass,
2089 const JSFunctionSpec* Methods, const bool needsFuseProperty>
2090 bool GlobalObject::initObjectIteratorProto(JSContext* cx,
2091 Handle<GlobalObject*> global,
2092 Handle<JSAtom*> tag) {
2093 if (global->hasBuiltinProto(Kind)) {
2094 return true;
2095 }
2096
2097 RootedObject iteratorProto(
2098 cx, GlobalObject::getOrCreateIteratorPrototype(cx, global));
2099 if (!iteratorProto) {
2100 return false;
2101 }
2102
2103 RootedObject proto(cx, GlobalObject::createBlankPrototypeInheriting(
2104 cx, ProtoClass, iteratorProto));
2105 if (!proto || !DefinePropertiesAndFunctions(cx, proto, nullptr, Methods) ||
2106 (tag && !DefineToStringTag(cx, proto, tag))) {
2107 return false;
2108 }
2109
2110 if constexpr (needsFuseProperty) {
2111 if (!JSObject::setHasFuseProperty(cx, proto)) {
2112 return false;
2113 }
2114 }
2115
2116 global->initBuiltinProto(Kind, proto);
2117 return true;
2118 }
2119
2120 /* static */
2121 NativeObject* GlobalObject::getOrCreateArrayIteratorPrototype(
2122 JSContext* cx, Handle<GlobalObject*> global) {
2123 return MaybeNativeObject(getOrCreateBuiltinProto(
2124 cx, global, ProtoKind::ArrayIteratorProto,
2125 cx->names().Array_Iterator_.toHandle(),
2126 initObjectIteratorProto<
2127 ProtoKind::ArrayIteratorProto, &ArrayIteratorPrototypeClass,
2128 array_iterator_methods, /* hasFuseProperty= */ true>));
2129 }
2130
2131 /* static */
2132 JSObject* GlobalObject::getOrCreateStringIteratorPrototype(
2133 JSContext* cx, Handle<GlobalObject*> global) {
2134 return getOrCreateBuiltinProto(
2135 cx, global, ProtoKind::StringIteratorProto,
2136 cx->names().String_Iterator_.toHandle(),
2137 initObjectIteratorProto<ProtoKind::StringIteratorProto,
2138 &StringIteratorPrototypeClass,
2139 string_iterator_methods>);
2140 }
2141
2142 /* static */
2143 JSObject* GlobalObject::getOrCreateRegExpStringIteratorPrototype(
2144 JSContext* cx, Handle<GlobalObject*> global) {
2145 return getOrCreateBuiltinProto(
2146 cx, global, ProtoKind::RegExpStringIteratorProto,
2147 cx->names().RegExp_String_Iterator_.toHandle(),
2148 initObjectIteratorProto<ProtoKind::RegExpStringIteratorProto,
2149 &RegExpStringIteratorPrototypeClass,
2150 regexp_string_iterator_methods>);
2151 }
2152
2153 #ifdef NIGHTLY_BUILD
2154 /* static */
2155 JSObject* GlobalObject::getOrCreateIteratorRangePrototype(
2156 JSContext* cx, Handle<GlobalObject*> global) {
2157 return getOrCreateBuiltinProto(
2158 cx, global, ProtoKind::IteratorRangeProto,
2159 cx->names().RegExp_String_Iterator_.toHandle(),
2160 initObjectIteratorProto<ProtoKind::IteratorRangeProto,
2161 &IteratorRangePrototypeClass,
2162 iterator_range_methods>);
2163 }
2164 #endif
2165
2166 // Iterator Helper Proposal 2.1.3.1 Iterator()
2167 // https://tc39.es/proposal-iterator-helpers/#sec-iterator as of revision
2168 // ed6e15a
2169 static bool IteratorConstructor(JSContext* cx, unsigned argc, Value* vp) {
2170 CallArgs args = CallArgsFromVp(argc, vp);
2171
2172 // Step 1.
2173 if (!ThrowIfNotConstructing(cx, args, "Iterator")) {
2174 return false;
2175 }
2176 // Throw TypeError if NewTarget is the active function object, preventing the
2177 // Iterator constructor from being used directly.
2178 if (args.callee() == args.newTarget().toObject()) {
2179 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2180 JSMSG_BOGUS_CONSTRUCTOR, "Iterator");
2181 return false;
2182 }
2183
2184 // Step 2.
2185 RootedObject proto(cx);
2186 if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_Iterator, &proto)) {
2187 return false;
2188 }
2189
2190 JSObject* obj = NewObjectWithClassProto<IteratorObject>(cx, proto);
2191 if (!obj) {
2192 return false;
2193 }
2194
2195 args.rval().setObject(*obj);
2196 return true;
2197 }
2198
2199 static const ClassSpec IteratorObjectClassSpec = {
2200 GenericCreateConstructor<IteratorConstructor, 0, gc::AllocKind::FUNCTION>,
2201 GenericCreatePrototype<IteratorObject>,
2202 iterator_static_methods,
2203 nullptr,
2204 iterator_methods,
2205 iterator_properties,
2206 IteratorObject::finishInit,
2207 };
2208
2209 const JSClass IteratorObject::class_ = {
2210 "Iterator",
2211 JSCLASS_HAS_CACHED_PROTO(JSProto_Iterator),
2212 JS_NULL_CLASS_OPS,
2213 &IteratorObjectClassSpec,
2214 };
2215
2216 const JSClass IteratorObject::protoClass_ = {
2217 "Iterator.prototype",
2218 JSCLASS_HAS_CACHED_PROTO(JSProto_Iterator),
2219 JS_NULL_CLASS_OPS,
2220 &IteratorObjectClassSpec,
2221 };
2222
2223 /* static */ bool IteratorObject::finishInit(JSContext* cx, HandleObject ctor,
2224 HandleObject proto) {
2225 Rooted<PropertyKey> id(cx, NameToId(cx->names().constructor));
2226 return JS_DefinePropertyById(cx, proto, id, constructorGetter,
2227 constructorSetter, 0);
2228 }
2229
2230 // Set up WrapForValidIteratorObject class and its prototype.
2231 static const JSFunctionSpec wrap_for_valid_iterator_methods[] = {
2232 JS_SELF_HOSTED_FN("next", "WrapForValidIteratorNext", 0, 0),
2233 JS_SELF_HOSTED_FN("return", "WrapForValidIteratorReturn", 0, 0),
2234 JS_FS_END,
2235 };
2236
2237 static const JSClass WrapForValidIteratorPrototypeClass = {
2238 "Wrap For Valid Iterator",
2239 0,
2240 };
2241
2242 const JSClass WrapForValidIteratorObject::class_ = {
2243 "Wrap For Valid Iterator",
2244 JSCLASS_HAS_RESERVED_SLOTS(WrapForValidIteratorObject::SlotCount),
2245 };
2246
2247 /* static */
2248 NativeObject* GlobalObject::getOrCreateWrapForValidIteratorPrototype(
2249 JSContext* cx, Handle<GlobalObject*> global) {
2250 return MaybeNativeObject(getOrCreateBuiltinProto(
2251 cx, global, ProtoKind::WrapForValidIteratorProto,
2252 Handle<JSAtom*>(nullptr),
2253 initObjectIteratorProto<ProtoKind::WrapForValidIteratorProto,
2254 &WrapForValidIteratorPrototypeClass,
2255 wrap_for_valid_iterator_methods>));
2256 }
2257
2258 WrapForValidIteratorObject* js::NewWrapForValidIterator(JSContext* cx) {
2259 RootedObject proto(cx, GlobalObject::getOrCreateWrapForValidIteratorPrototype(
2260 cx, cx->global()));
2261 if (!proto) {
2262 return nullptr;
2263 }
2264 return NewObjectWithGivenProto<WrapForValidIteratorObject>(cx, proto);
2265 }
2266
2267 // Common iterator object returned by Iterator Helper methods.
2268 static const JSFunctionSpec iterator_helper_methods[] = {
2269 JS_SELF_HOSTED_FN("next", "IteratorHelperNext", 0, 0),
2270 JS_SELF_HOSTED_FN("return", "IteratorHelperReturn", 0, 0),
2271 JS_FS_END,
2272 };
2273
2274 static const JSClass IteratorHelperPrototypeClass = {
2275 "Iterator Helper",
2276 0,
2277 };
2278
2279 const JSClass IteratorHelperObject::class_ = {
2280 "Iterator Helper",
2281 JSCLASS_HAS_RESERVED_SLOTS(IteratorHelperObject::SlotCount),
2282 };
2283
2284 #ifdef NIGHTLY_BUILD
2285 const JSClass IteratorRangeObject::class_ = {
2286 "IteratorRange",
2287 JSCLASS_HAS_RESERVED_SLOTS(IteratorRangeSlotCount),
2288 };
2289 #endif
2290
2291 /* static */
2292 NativeObject* GlobalObject::getOrCreateIteratorHelperPrototype(
2293 JSContext* cx, Handle<GlobalObject*> global) {
2294 return MaybeNativeObject(getOrCreateBuiltinProto(
2295 cx, global, ProtoKind::IteratorHelperProto,
2296 cx->names().Iterator_Helper_.toHandle(),
2297 initObjectIteratorProto<ProtoKind::IteratorHelperProto,
2298 &IteratorHelperPrototypeClass,
2299 iterator_helper_methods>));
2300 }
2301
2302 IteratorHelperObject* js::NewIteratorHelper(JSContext* cx) {
2303 RootedObject proto(
2304 cx, GlobalObject::getOrCreateIteratorHelperPrototype(cx, cx->global()));
2305 if (!proto) {
2306 return nullptr;
2307 }
2308 return NewObjectWithGivenProto<IteratorHelperObject>(cx, proto);
2309 }
2310
2311 bool js::IterableToArray(JSContext* cx, HandleValue iterable,
2312 MutableHandle<ArrayObject*> array) {
2313 JS::ForOfIterator iterator(cx);
2314 if (!iterator.init(iterable, JS::ForOfIterator::ThrowOnNonIterable)) {
2315 return false;
2316 }
2317
2318 array.set(NewDenseEmptyArray(cx));
2319 if (!array) {
2320 return false;
2321 }
2322
2323 RootedValue nextValue(cx);
2324 while (true) {
2325 bool done;
2326 if (!iterator.next(&nextValue, &done)) {
2327 return false;
2328 }
2329 if (done) {
2330 break;
2331 }
2332
2333 if (!NewbornArrayPush(cx, array, nextValue)) {
2334 return false;
2335 }
2336 }
2337 return true;
2338 }
2339
2340 bool js::HasOptimizableArrayIteratorPrototype(JSContext* cx) {
2341 // Return true if %ArrayIteratorPrototype% does not have (re)defined `next`
2342 // and `return` properties.
2343 return cx->realm()->realmFuses.optimizeArrayIteratorPrototypeFuse.intact();
2344 }
2345
2346 template <MustBePacked Packed>
2347 bool js::IsArrayWithDefaultIterator(JSObject* obj, JSContext* cx) {
2348 if constexpr (Packed == MustBePacked::Yes) {
2349 if (!IsPackedArray(obj)) {
2350 return false;
2351 }
2352 } else {
2353 if (!obj->is<ArrayObject>()) {
2354 return false;
2355 }
2356 }
2357 ArrayObject* arr = &obj->as<ArrayObject>();
2358
2359 // Ensure Array.prototype[@@iterator] and %ArrayIteratorPrototype% haven't
2360 // been mutated in a way that affects the iterator protocol.
2361 if (!arr->realm()->realmFuses.optimizeGetIteratorFuse.intact()) {
2362 return false;
2363 }
2364
2365 // Ensure the array has Array.prototype as prototype and doesn't have an own
2366 // @@iterator property.
2367 //
2368 // Most arrays have the default array shape so we have a fast path for this
2369 // case.
2370 GlobalObject& global = arr->global();
2371 if (arr->shape() == global.maybeArrayShapeWithDefaultProto()) {
2372 return true;
2373 }
2374
2375 NativeObject* arrayProto = global.maybeGetArrayPrototype();
2376 if (!arrayProto || arr->staticPrototype() != arrayProto) {
2377 return false;
2378 }
2379 if (arr->containsPure(PropertyKey::Symbol(cx->wellKnownSymbols().iterator))) {
2380 return false;
2381 }
2382
2383 return true;
2384 }
2385
2386 template bool js::IsArrayWithDefaultIterator<MustBePacked::No>(JSObject* obj,
2387 JSContext* cx);
2388 template bool js::IsArrayWithDefaultIterator<MustBePacked::Yes>(JSObject* obj,
2389 JSContext* cx);
2390
2391 template <typename ObjectT, JSProtoKey ProtoKey>
2392 static bool IsMapOrSetObjectWithDefaultIterator(JSObject* objArg,
2393 JSContext* cx) {
2394 if (!objArg->is<ObjectT>()) {
2395 return false;
2396 }
2397 auto* obj = &objArg->as<ObjectT>();
2398
2399 // Ensure {Map,Set}.prototype[@@iterator] and %{Map,Set}IteratorPrototype%
2400 // haven't been mutated in a way that affects the iterator protocol.
2401 //
2402 // Note: this doesn't guard against `return` properties on the iterator
2403 // prototype, so this should only be used in places where we don't have to
2404 // call `IteratorClose`.
2405 if constexpr (std::is_same_v<ObjectT, MapObject>) {
2406 if (!obj->realm()->realmFuses.optimizeMapObjectIteratorFuse.intact()) {
2407 return false;
2408 }
2409 } else {
2410 static_assert(std::is_same_v<ObjectT, SetObject>);
2411 if (!obj->realm()->realmFuses.optimizeSetObjectIteratorFuse.intact()) {
2412 return false;
2413 }
2414 }
2415
2416 // Ensure the object has the builtin prototype as proto.
2417 GlobalObject& global = obj->global();
2418 JSObject* proto = global.maybeGetPrototype(ProtoKey);
2419 if (!proto || obj->staticPrototype() != proto) {
2420 return false;
2421 }
2422
2423 // Ensure the Map or Set object doesn't have an own @@iterator property.
2424 // Most Maps and Sets have no own properties so we have a fast path for this
2425 // case.
2426 if (obj->empty()) {
2427 return true;
2428 }
2429 if (obj->containsPure(PropertyKey::Symbol(cx->wellKnownSymbols().iterator))) {
2430 return false;
2431 }
2432 return true;
2433 }
2434 bool js::IsMapObjectWithDefaultIterator(JSObject* obj, JSContext* cx) {
2435 return IsMapOrSetObjectWithDefaultIterator<MapObject, JSProto_Map>(obj, cx);
2436 }
2437
2438 bool js::IsSetObjectWithDefaultIterator(JSObject* obj, JSContext* cx) {
2439 return IsMapOrSetObjectWithDefaultIterator<SetObject, JSProto_Set>(obj, cx);
2440 }