-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIteration.cpp
1740 lines (1461 loc) · 54.7 KB
/
Iteration.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* JavaScript iterators. */
#include "vm/Iteration.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Likely.h"
#include "mozilla/Maybe.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Unused.h"
#include <algorithm>
#include <new>
#include "jstypes.h"
#include "builtin/Array.h"
#include "builtin/SelfHostingDefines.h"
#include "ds/Sort.h"
#include "gc/FreeOp.h"
#include "gc/Marking.h"
#include "js/PropertySpec.h"
#include "js/Proxy.h"
#include "util/Poison.h"
#include "vm/BytecodeUtil.h"
#include "vm/GlobalObject.h"
#include "vm/Interpreter.h"
#include "vm/JSAtom.h"
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/JSScript.h"
#include "vm/NativeObject.h" // js::PlainObject
#include "vm/Shape.h"
#include "vm/TypedArrayObject.h"
#include "vm/Compartment-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/PlainObject-inl.h" // js::PlainObject::createWithTemplate
#include "vm/ReceiverGuard-inl.h"
#include "vm/Stack-inl.h"
#include "vm/StringType-inl.h"
using namespace js;
using mozilla::ArrayEqual;
using mozilla::DebugOnly;
using mozilla::Maybe;
using mozilla::PodCopy;
using RootedPropertyIteratorObject = Rooted<PropertyIteratorObject*>;
static const gc::AllocKind ITERATOR_FINALIZE_KIND =
gc::AllocKind::OBJECT2_BACKGROUND;
// Beware! This function may have to trace incompletely-initialized
// |NativeIterator| allocations if the |IdToString| in that constructor recurs
// into this code.
void NativeIterator::trace(JSTracer* trc) {
TraceNullableEdge(trc, &objectBeingIterated_, "objectBeingIterated_");
TraceNullableEdge(trc, &iterObj_, "iterObj");
// The limits below are correct at every instant of |NativeIterator|
// initialization, with the end-pointer incremented as each new guard is
// created, so they're safe to use here.
std::for_each(guardsBegin(), guardsEnd(),
[trc](HeapReceiverGuard& guard) { guard.trace(trc); });
// But as properties must be created *before* guards, |propertiesBegin()|
// that depends on |guardsEnd()| having its final value can't safely be
// used. Until this is fully initialized, use |propertyCursor_| instead,
// which points at the start of properties even in partially initialized
// |NativeIterator|s. (|propertiesEnd()| is safe at all times with respect
// to the properly-chosen beginning.)
//
// Note that we must trace all properties (not just those not yet visited,
// or just visited, due to |NativeIterator::previousPropertyWas|) for
// |NativeIterator|s to be reusable.
GCPtrLinearString* begin =
MOZ_LIKELY(isInitialized()) ? propertiesBegin() : propertyCursor_;
std::for_each(begin, propertiesEnd(), [trc](GCPtrLinearString& prop) {
// Properties begin life non-null and never *become*
// null. (Deletion-suppression will shift trailing
// properties over a deleted property in the properties
// array, but it doesn't null them out.)
TraceEdge(trc, &prop, "prop");
});
}
using IdSet = GCHashSet<jsid, DefaultHasher<jsid>>;
template <bool CheckForDuplicates>
static inline bool Enumerate(JSContext* cx, HandleObject pobj, jsid id,
bool enumerable, unsigned flags,
MutableHandle<IdSet> visited,
MutableHandleIdVector props) {
if (CheckForDuplicates) {
// If we've already seen this, we definitely won't add it.
IdSet::AddPtr p = visited.lookupForAdd(id);
if (MOZ_UNLIKELY(!!p)) {
return true;
}
// It's not necessary to add properties to the hash set at the end of
// the prototype chain, but custom enumeration behaviors might return
// duplicated properties, so always add in such cases.
if (pobj->is<ProxyObject>() || pobj->staticPrototype() ||
pobj->getClass()->getNewEnumerate()) {
if (!visited.add(p, id)) {
return false;
}
}
}
if (!enumerable && !(flags & JSITER_HIDDEN)) {
return true;
}
// Symbol-keyed properties and nonenumerable properties are skipped unless
// the caller specifically asks for them. A caller can also filter out
// non-symbols by asking for JSITER_SYMBOLSONLY. PrivateName symbols are
// always skipped.
if (JSID_IS_SYMBOL(id)) {
if (!(flags & JSITER_SYMBOLS) || JSID_TO_SYMBOL(id)->isPrivateName()) {
return true;
}
} else {
if ((flags & JSITER_SYMBOLSONLY)) {
return true;
}
}
return props.append(id);
}
static bool EnumerateExtraProperties(JSContext* cx, HandleObject obj,
unsigned flags,
MutableHandle<IdSet> visited,
MutableHandleIdVector props) {
MOZ_ASSERT(obj->getClass()->getNewEnumerate());
RootedIdVector properties(cx);
bool enumerableOnly = !(flags & JSITER_HIDDEN);
if (!obj->getClass()->getNewEnumerate()(cx, obj, &properties,
enumerableOnly)) {
return false;
}
RootedId id(cx);
for (size_t n = 0; n < properties.length(); n++) {
id = properties[n];
// The enumerate hook does not indicate whether the properties
// it returns are enumerable or not. Since we already passed
// `enumerableOnly` to the hook to filter out non-enumerable
// properties, it doesn't really matter what we pass here.
bool enumerable = true;
if (!Enumerate<true>(cx, obj, id, enumerable, flags, visited, props)) {
return false;
}
}
return true;
}
static bool SortComparatorIntegerIds(jsid a, jsid b, bool* lessOrEqualp) {
uint32_t indexA, indexB;
MOZ_ALWAYS_TRUE(IdIsIndex(a, &indexA));
MOZ_ALWAYS_TRUE(IdIsIndex(b, &indexB));
*lessOrEqualp = (indexA <= indexB);
return true;
}
template <bool CheckForDuplicates>
static bool EnumerateNativeProperties(JSContext* cx, HandleNativeObject pobj,
unsigned flags,
MutableHandle<IdSet> visited,
MutableHandleIdVector props) {
bool enumerateSymbols;
if (flags & JSITER_SYMBOLSONLY) {
enumerateSymbols = true;
} else {
// Collect any dense elements from this object.
size_t firstElemIndex = props.length();
size_t initlen = pobj->getDenseInitializedLength();
const Value* vp = pobj->getDenseElements();
bool hasHoles = false;
for (size_t i = 0; i < initlen; ++i, ++vp) {
if (vp->isMagic(JS_ELEMENTS_HOLE)) {
hasHoles = true;
} else {
// Dense arrays never get so large that i would not fit into an
// integer id.
if (!Enumerate<CheckForDuplicates>(cx, pobj, INT_TO_JSID(i),
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
}
// Collect any typed array or shared typed array elements from this
// object.
if (pobj->is<TypedArrayObject>()) {
size_t len = pobj->as<TypedArrayObject>().length();
for (size_t i = 0; i < len; i++) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, INT_TO_JSID(i),
/* enumerable = */ true, flags,
visited, props)) {
return false;
}
}
}
// Collect any sparse elements from this object.
bool isIndexed = pobj->isIndexed();
if (isIndexed) {
// If the dense elements didn't have holes, we don't need to include
// them in the sort.
if (!hasHoles) {
firstElemIndex = props.length();
}
for (Shape::Range<NoGC> r(pobj->lastProperty()); !r.empty();
r.popFront()) {
Shape& shape = r.front();
jsid id = shape.propid();
uint32_t dummy;
if (IdIsIndex(id, &dummy)) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, shape.enumerable(),
flags, visited, props)) {
return false;
}
}
}
MOZ_ASSERT(firstElemIndex <= props.length());
jsid* ids = props.begin() + firstElemIndex;
size_t n = props.length() - firstElemIndex;
RootedIdVector tmp(cx);
if (!tmp.resize(n)) {
return false;
}
PodCopy(tmp.begin(), ids, n);
if (!MergeSort(ids, n, tmp.begin(), SortComparatorIntegerIds)) {
return false;
}
}
size_t initialLength = props.length();
/* Collect all unique property names from this object's shape. */
bool symbolsFound = false;
Shape::Range<NoGC> r(pobj->lastProperty());
for (; !r.empty(); r.popFront()) {
Shape& shape = r.front();
jsid id = shape.propid();
if (JSID_IS_SYMBOL(id)) {
symbolsFound = true;
continue;
}
uint32_t dummy;
if (isIndexed && IdIsIndex(id, &dummy)) {
continue;
}
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, shape.enumerable(),
flags, visited, props)) {
return false;
}
}
std::reverse(props.begin() + initialLength, props.end());
enumerateSymbols = symbolsFound && (flags & JSITER_SYMBOLS);
}
if (enumerateSymbols) {
// Do a second pass to collect symbols. ES6 draft rev 25 (2014 May 22)
// 9.1.12 requires that all symbols appear after all strings in the
// result.
size_t initialLength = props.length();
for (Shape::Range<NoGC> r(pobj->lastProperty()); !r.empty(); r.popFront()) {
Shape& shape = r.front();
jsid id = shape.propid();
if (JSID_IS_SYMBOL(id)) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, id, shape.enumerable(),
flags, visited, props)) {
return false;
}
}
}
std::reverse(props.begin() + initialLength, props.end());
}
return true;
}
static bool EnumerateNativeProperties(JSContext* cx, HandleNativeObject pobj,
unsigned flags,
MutableHandle<IdSet> visited,
MutableHandleIdVector props,
bool checkForDuplicates) {
if (checkForDuplicates) {
return EnumerateNativeProperties<true>(cx, pobj, flags, visited, props);
}
return EnumerateNativeProperties<false>(cx, pobj, flags, visited, props);
}
template <bool CheckForDuplicates>
static bool EnumerateProxyProperties(JSContext* cx, HandleObject pobj,
unsigned flags,
MutableHandle<IdSet> visited,
MutableHandleIdVector props) {
MOZ_ASSERT(pobj->is<ProxyObject>());
RootedIdVector proxyProps(cx);
if (flags & JSITER_HIDDEN || flags & JSITER_SYMBOLS) {
// This gets all property keys, both strings and symbols. The call to
// Enumerate in the loop below will filter out unwanted keys, per the
// flags.
if (!Proxy::ownPropertyKeys(cx, pobj, &proxyProps)) {
return false;
}
Rooted<PropertyDescriptor> desc(cx);
for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
bool enumerable = false;
// We need to filter, if the caller just wants enumerable symbols.
if (!(flags & JSITER_HIDDEN)) {
if (!Proxy::getOwnPropertyDescriptor(cx, pobj, proxyProps[n], &desc)) {
return false;
}
enumerable = desc.enumerable();
}
if (!Enumerate<CheckForDuplicates>(cx, pobj, proxyProps[n], enumerable,
flags, visited, props)) {
return false;
}
}
return true;
}
// Returns enumerable property names (no symbols).
if (!Proxy::getOwnEnumerablePropertyKeys(cx, pobj, &proxyProps)) {
return false;
}
for (size_t n = 0, len = proxyProps.length(); n < len; n++) {
if (!Enumerate<CheckForDuplicates>(cx, pobj, proxyProps[n], true, flags,
visited, props)) {
return false;
}
}
return true;
}
#ifdef JS_MORE_DETERMINISTIC
struct SortComparatorIds {
JSContext* const cx;
SortComparatorIds(JSContext* cx) : cx(cx) {}
bool operator()(jsid a, jsid b, bool* lessOrEqualp) {
// Pick an arbitrary order on jsids that is as stable as possible
// across executions.
if (a == b) {
*lessOrEqualp = true;
return true;
}
size_t ta = JSID_BITS(a) & JSID_TYPE_MASK;
size_t tb = JSID_BITS(b) & JSID_TYPE_MASK;
if (ta != tb) {
*lessOrEqualp = (ta <= tb);
return true;
}
if (JSID_IS_INT(a)) {
*lessOrEqualp = (JSID_TO_INT(a) <= JSID_TO_INT(b));
return true;
}
RootedString astr(cx), bstr(cx);
if (JSID_IS_SYMBOL(a)) {
MOZ_ASSERT(JSID_IS_SYMBOL(b));
MOZ_ASSERT(!JSID_TO_SYMBOL(a)->isPrivateName());
MOZ_ASSERT(!JSID_TO_SYMBOL(b)->isPrivateName());
JS::SymbolCode ca = JSID_TO_SYMBOL(a)->code();
JS::SymbolCode cb = JSID_TO_SYMBOL(b)->code();
if (ca != cb) {
*lessOrEqualp = uint32_t(ca) <= uint32_t(cb);
return true;
}
MOZ_ASSERT(ca == JS::SymbolCode::InSymbolRegistry ||
ca == JS::SymbolCode::UniqueSymbol);
astr = JSID_TO_SYMBOL(a)->description();
bstr = JSID_TO_SYMBOL(b)->description();
if (!astr || !bstr) {
*lessOrEqualp = !astr;
return true;
}
// Fall through to string comparison on the descriptions. The sort
// order is nondeterministic if two different unique symbols have
// the same description.
} else {
astr = IdToString(cx, a);
if (!astr) {
return false;
}
bstr = IdToString(cx, b);
if (!bstr) {
return false;
}
}
int32_t result;
if (!CompareStrings(cx, astr, bstr, &result)) {
return false;
}
*lessOrEqualp = (result <= 0);
return true;
}
};
#endif /* JS_MORE_DETERMINISTIC */
static bool Snapshot(JSContext* cx, HandleObject pobj_, unsigned flags,
MutableHandleIdVector props) {
Rooted<IdSet> visited(cx, IdSet(cx));
RootedObject pobj(cx, pobj_);
// Don't check for duplicates if we're only interested in own properties.
// This does the right thing for most objects: native objects don't have
// duplicate property ids and we allow the [[OwnPropertyKeys]] proxy trap to
// return duplicates.
//
// The only special case is when the object has a newEnumerate hook: it
// can return duplicate properties and we have to filter them. This is
// handled below.
bool checkForDuplicates = !(flags & JSITER_OWNONLY);
do {
if (pobj->getClass()->getNewEnumerate()) {
if (!EnumerateExtraProperties(cx, pobj, flags, &visited, props)) {
return false;
}
if (pobj->isNative()) {
if (!EnumerateNativeProperties(cx, pobj.as<NativeObject>(), flags,
&visited, props, true)) {
return false;
}
}
} else if (pobj->isNative()) {
// Give the object a chance to resolve all lazy properties
if (JSEnumerateOp enumerate = pobj->getClass()->getEnumerate()) {
if (!enumerate(cx, pobj.as<NativeObject>())) {
return false;
}
}
if (!EnumerateNativeProperties(cx, pobj.as<NativeObject>(), flags,
&visited, props, checkForDuplicates)) {
return false;
}
} else if (pobj->is<ProxyObject>()) {
if (checkForDuplicates) {
if (!EnumerateProxyProperties<true>(cx, pobj, flags, &visited, props)) {
return false;
}
} else {
if (!EnumerateProxyProperties<false>(cx, pobj, flags, &visited,
props)) {
return false;
}
}
} else {
MOZ_CRASH("non-native objects must have an enumerate op");
}
if (flags & JSITER_OWNONLY) {
break;
}
if (!GetPrototype(cx, pobj, &pobj)) {
return false;
}
// The [[Prototype]] chain might be cyclic.
if (!CheckForInterrupt(cx)) {
return false;
}
} while (pobj != nullptr);
#ifdef JS_MORE_DETERMINISTIC
/*
* In some cases the enumeration order for an object depends on the
* execution mode (interpreter vs. JIT), especially for native objects
* with a class enumerate hook (where resolving a property changes the
* resulting enumeration order). These aren't really bugs, but the
* differences can change the generated output and confuse correctness
* fuzzers, so we sort the ids if such a fuzzer is running.
*
* We don't do this in the general case because (a) doing so is slow,
* and (b) it also breaks the web, which expects enumeration order to
* follow the order in which properties are added, in certain cases.
* Since ECMA does not specify an enumeration order for objects, both
* behaviors are technically correct to do.
*/
jsid* ids = props.begin();
size_t n = props.length();
RootedIdVector tmp(cx);
if (!tmp.resize(n)) {
return false;
}
PodCopy(tmp.begin(), ids, n);
if (!MergeSort(ids, n, tmp.begin(), SortComparatorIds(cx))) {
return false;
}
#endif /* JS_MORE_DETERMINISTIC */
return true;
}
JS_FRIEND_API bool js::GetPropertyKeys(JSContext* cx, HandleObject obj,
unsigned flags,
MutableHandleIdVector props) {
return Snapshot(cx, obj,
flags & (JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS |
JSITER_SYMBOLSONLY),
props);
}
static inline void RegisterEnumerator(ObjectRealm& realm, NativeIterator* ni) {
// Register non-escaping native enumerators (for-in) with the current
// context.
ni->link(realm.enumerators);
MOZ_ASSERT(!ni->isActive());
ni->markActive();
}
static PropertyIteratorObject* NewPropertyIteratorObject(JSContext* cx) {
RootedObjectGroup group(
cx, ObjectGroup::defaultNewGroup(cx, &PropertyIteratorObject::class_,
TaggedProto(nullptr)));
if (!group) {
return nullptr;
}
const JSClass* clasp = &PropertyIteratorObject::class_;
RootedShape shape(cx,
EmptyShape::getInitialShape(cx, clasp, TaggedProto(nullptr),
ITERATOR_FINALIZE_KIND));
if (!shape) {
return nullptr;
}
JSObject* obj;
JS_TRY_VAR_OR_RETURN_NULL(
cx, obj,
NativeObject::create(cx, ITERATOR_FINALIZE_KIND,
GetInitialHeap(GenericObject, group), shape, group));
PropertyIteratorObject* res = &obj->as<PropertyIteratorObject>();
// CodeGenerator::visitIteratorStartO assumes the iterator object is not
// inside the nursery when deciding whether a barrier is necessary.
MOZ_ASSERT(!js::gc::IsInsideNursery(res));
MOZ_ASSERT(res->numFixedSlots() == PropertyIteratorObject::NUM_FIXED_SLOTS);
return res;
}
static inline size_t ExtraStringCount(size_t propertyCount, size_t guardCount) {
static_assert(sizeof(ReceiverGuard) == 2 * sizeof(GCPtrLinearString),
"NativeIterators are allocated in space for 1) themselves, "
"2) the properties a NativeIterator iterates (as "
"GCPtrLinearStrings), and 3) |numGuards| HeapReceiverGuard "
"objects; the additional-length calculation below assumes "
"this size-relationship when determining the extra space to "
"allocate");
return propertyCount + guardCount * 2;
}
static inline size_t AllocationSize(size_t propertyCount, size_t guardCount) {
return sizeof(NativeIterator) + (ExtraStringCount(propertyCount, guardCount) *
sizeof(GCPtrLinearString));
}
static PropertyIteratorObject* CreatePropertyIterator(
JSContext* cx, Handle<JSObject*> objBeingIterated, HandleIdVector props,
uint32_t numGuards, uint32_t guardKey) {
Rooted<PropertyIteratorObject*> propIter(cx, NewPropertyIteratorObject(cx));
if (!propIter) {
return nullptr;
}
void* mem = cx->pod_malloc_with_extra<NativeIterator, GCPtrLinearString>(
ExtraStringCount(props.length(), numGuards));
if (!mem) {
return nullptr;
}
// This also registers |ni| with |propIter|.
bool hadError = false;
NativeIterator* ni = new (mem) NativeIterator(
cx, propIter, objBeingIterated, props, numGuards, guardKey, &hadError);
if (hadError) {
return nullptr;
}
ObjectRealm& realm = objBeingIterated ? ObjectRealm::get(objBeingIterated)
: ObjectRealm::get(propIter);
RegisterEnumerator(realm, ni);
return propIter;
}
/**
* Initialize a sentinel NativeIterator whose purpose is only to act as the
* start/end of the circular linked list of NativeIterators in
* ObjectRealm::enumerators.
*/
NativeIterator::NativeIterator() {
// Do our best to enforce that nothing in |this| except the two fields set
// below is ever observed.
AlwaysPoison(static_cast<void*>(this), JS_NEW_NATIVE_ITERATOR_PATTERN,
sizeof(*this), MemCheckKind::MakeUndefined);
// These are the only two fields in sentinel NativeIterators that are
// examined, in ObjectRealm::traceWeakNativeIterators. Everything else is
// only examined *if* it's a NativeIterator being traced by a
// PropertyIteratorObject that owns it, and nothing owns this iterator.
prev_ = next_ = this;
}
NativeIterator* NativeIterator::allocateSentinel(JSContext* cx) {
NativeIterator* ni = js_new<NativeIterator>();
if (!ni) {
ReportOutOfMemory(cx);
return nullptr;
}
return ni;
}
/**
* Initialize a fresh NativeIterator.
*
* This definition is a bit tricky: some parts of initializing are fallible, so
* as we initialize, we must carefully keep this in GC-safe state (see
* NativeIterator::trace).
*/
NativeIterator::NativeIterator(JSContext* cx,
Handle<PropertyIteratorObject*> propIter,
Handle<JSObject*> objBeingIterated,
HandleIdVector props, uint32_t numGuards,
uint32_t guardKey, bool* hadError)
: objectBeingIterated_(objBeingIterated),
iterObj_(propIter),
// NativeIterator initially acts (before full initialization) as if it
// contains no guards...
guardsEnd_(guardsBegin()),
// ...and no properties.
propertyCursor_(
reinterpret_cast<GCPtrLinearString*>(guardsBegin() + numGuards)),
propertiesEnd_(propertyCursor_),
guardKey_(guardKey),
flagsAndCount_(0) // note: no Flags::Initialized
{
MOZ_ASSERT(!*hadError);
// NOTE: This must be done first thing: PropertyIteratorObject::finalize
// can only free |this| (and not leak it) if this has happened.
propIter->setNativeIterator(this);
if (!setInitialPropertyCount(props.length())) {
ReportAllocationOverflow(cx);
*hadError = true;
return;
}
size_t nbytes = AllocationSize(props.length(), numGuards);
AddCellMemory(propIter, nbytes, MemoryUse::NativeIterator);
for (size_t i = 0, len = props.length(); i < len; i++) {
JSLinearString* str = IdToString(cx, props[i]);
if (!str) {
*hadError = true;
return;
}
// Placement-new the next property string at the end of the currently
// computed property strings.
GCPtrLinearString* loc = propertiesEnd_;
// Increase the overall property string count before initializing the
// property string, so this construction isn't on a location not known
// to the GC yet.
propertiesEnd_++;
new (loc) GCPtrLinearString(str);
}
if (numGuards > 0) {
// Construct guards into the guard array. Also recompute the guard key,
// which incorporates Shape* and ObjectGroup* addresses that could have
// changed during a GC triggered in (among other places) |IdToString|
//. above.
JSObject* pobj = objBeingIterated;
#ifdef DEBUG
uint32_t i = 0;
#endif
uint32_t key = 0;
do {
ReceiverGuard guard(pobj);
// Placement-new the next HeapReceiverGuard at the end of the
// currently initialized HeapReceiverGuards.
HeapReceiverGuard* loc = guardsEnd_;
// Increase the overall guard-count before initializing the
// HeapReceiverGuard, so this construction isn't on a location not
// known to the GC.
guardsEnd_++;
#ifdef DEBUG
i++;
#endif
new (loc) HeapReceiverGuard(guard);
key = mozilla::AddToHash(key, guard.hash());
// The one caller of this method that passes |numGuards > 0|, does
// so only if the entire chain consists of cacheable objects (that
// necessarily have static prototypes).
pobj = pobj->staticPrototype();
} while (pobj);
guardKey_ = key;
MOZ_ASSERT(i == numGuards);
}
// |guardsEnd_| is now guaranteed to point at the start of properties, so
// we can mark this initialized.
MOZ_ASSERT(static_cast<void*>(guardsEnd_) == propertyCursor_);
markInitialized();
MOZ_ASSERT(!*hadError);
}
inline size_t NativeIterator::allocationSize() const {
size_t numGuards = guardsEnd() - guardsBegin();
return AllocationSize(initialPropertyCount(), numGuards);
}
/* static */
bool IteratorHashPolicy::match(PropertyIteratorObject* obj,
const Lookup& lookup) {
NativeIterator* ni = obj->getNativeIterator();
if (ni->guardKey() != lookup.key || ni->guardCount() != lookup.numGuards) {
return false;
}
return ArrayEqual(reinterpret_cast<ReceiverGuard*>(ni->guardsBegin()),
lookup.guards, ni->guardCount());
}
static inline bool CanCompareIterableObjectToCache(JSObject* obj) {
if (obj->isNative()) {
return obj->as<NativeObject>().getDenseInitializedLength() == 0;
}
return false;
}
using ReceiverGuardVector = Vector<ReceiverGuard, 8>;
static MOZ_ALWAYS_INLINE PropertyIteratorObject* LookupInIteratorCache(
JSContext* cx, JSObject* obj, uint32_t* numGuards) {
MOZ_ASSERT(*numGuards == 0);
ReceiverGuardVector guards(cx);
uint32_t key = 0;
JSObject* pobj = obj;
do {
if (!CanCompareIterableObjectToCache(pobj)) {
return nullptr;
}
ReceiverGuard guard(pobj);
key = mozilla::AddToHash(key, guard.hash());
if (MOZ_UNLIKELY(!guards.append(guard))) {
cx->recoverFromOutOfMemory();
return nullptr;
}
pobj = pobj->staticPrototype();
} while (pobj);
MOZ_ASSERT(!guards.empty());
*numGuards = guards.length();
IteratorHashPolicy::Lookup lookup(guards.begin(), guards.length(), key);
auto p = ObjectRealm::get(obj).iteratorCache.lookup(lookup);
if (!p) {
return nullptr;
}
PropertyIteratorObject* iterobj = *p;
MOZ_ASSERT(iterobj->compartment() == cx->compartment());
NativeIterator* ni = iterobj->getNativeIterator();
if (!ni->isReusable()) {
return nullptr;
}
return iterobj;
}
static bool CanStoreInIteratorCache(JSObject* obj) {
do {
MOZ_ASSERT(obj->isNative());
MOZ_ASSERT(obj->as<NativeObject>().getDenseInitializedLength() == 0);
// Typed arrays have indexed properties not captured by the Shape guard.
// Enumerate hooks may add extra properties.
const JSClass* clasp = obj->getClass();
if (MOZ_UNLIKELY(IsTypedArrayClass(clasp))) {
return false;
}
if (MOZ_UNLIKELY(clasp->getNewEnumerate() || clasp->getEnumerate())) {
return false;
}
obj = obj->staticPrototype();
} while (obj);
return true;
}
static MOZ_MUST_USE bool StoreInIteratorCache(JSContext* cx, JSObject* obj,
PropertyIteratorObject* iterobj) {
MOZ_ASSERT(CanStoreInIteratorCache(obj));
NativeIterator* ni = iterobj->getNativeIterator();
MOZ_ASSERT(ni->guardCount() > 0);
IteratorHashPolicy::Lookup lookup(
reinterpret_cast<ReceiverGuard*>(ni->guardsBegin()), ni->guardCount(),
ni->guardKey());
ObjectRealm::IteratorCache& cache = ObjectRealm::get(obj).iteratorCache;
bool ok;
auto p = cache.lookupForAdd(lookup);
if (MOZ_LIKELY(!p)) {
ok = cache.add(p, iterobj);
} else {
// If we weren't able to use an existing cached iterator, just
// replace it.
cache.remove(p);
ok = cache.relookupOrAdd(p, lookup, iterobj);
}
if (!ok) {
ReportOutOfMemory(cx);
return false;
}
return true;
}
bool js::EnumerateProperties(JSContext* cx, HandleObject obj,
MutableHandleIdVector props) {
MOZ_ASSERT(props.empty());
if (MOZ_UNLIKELY(obj->is<ProxyObject>())) {
return Proxy::enumerate(cx, obj, props);
}
return Snapshot(cx, obj, 0, props);
}
static JSObject* GetIterator(JSContext* cx, HandleObject obj) {
MOZ_ASSERT(!obj->is<PropertyIteratorObject>());
MOZ_ASSERT(cx->compartment() == obj->compartment(),
"We may end up allocating shapes in the wrong zone!");
uint32_t numGuards = 0;
if (PropertyIteratorObject* iterobj =
LookupInIteratorCache(cx, obj, &numGuards)) {
NativeIterator* ni = iterobj->getNativeIterator();
ni->changeObjectBeingIterated(*obj);
RegisterEnumerator(ObjectRealm::get(obj), ni);
return iterobj;
}
if (numGuards > 0 && !CanStoreInIteratorCache(obj)) {
numGuards = 0;
}
RootedIdVector keys(cx);
if (!EnumerateProperties(cx, obj, &keys)) {
return nullptr;
}
if (obj->isSingleton() && !JSObject::setIteratedSingleton(cx, obj)) {
return nullptr;
}
MarkObjectGroupFlags(cx, obj, OBJECT_FLAG_ITERATED);
PropertyIteratorObject* iterobj =
CreatePropertyIterator(cx, obj, keys, numGuards, 0);
if (!iterobj) {
return nullptr;
}
cx->check(iterobj);
// Cache the iterator object.
if (numGuards > 0) {
if (!StoreInIteratorCache(cx, obj, iterobj)) {
return nullptr;
}
}
return iterobj;
}
PropertyIteratorObject* js::LookupInIteratorCache(JSContext* cx,
HandleObject obj) {
uint32_t numGuards = 0;
return LookupInIteratorCache(cx, obj, &numGuards);
}
// ES 2017 draft 7.4.7.
PlainObject* js::CreateIterResultObject(JSContext* cx, HandleValue value,
bool done) {
// Step 1 (implicit).
// Step 2.
Rooted<PlainObject*> templateObject(
cx, cx->realm()->getOrCreateIterResultTemplateObject(cx));
if (!templateObject) {
return nullptr;
}
PlainObject* resultObj;
JS_TRY_VAR_OR_RETURN_NULL(
cx, resultObj, PlainObject::createWithTemplate(cx, templateObject));
// Step 3.
resultObj->setSlot(Realm::IterResultObjectValueSlot, value);
// Step 4.
resultObj->setSlot(Realm::IterResultObjectDoneSlot,
done ? TrueHandleValue : FalseHandleValue);
// Step 5.
return resultObj;
}
PlainObject* Realm::getOrCreateIterResultTemplateObject(JSContext* cx) {
MOZ_ASSERT(cx->realm() == this);
if (iterResultTemplate_) {
return iterResultTemplate_;
}
PlainObject* templateObj =
createIterResultTemplateObject(cx, WithObjectPrototype::Yes);
iterResultTemplate_.set(templateObj);
return iterResultTemplate_;