-
Notifications
You must be signed in to change notification settings - Fork 54
/
NativeObject.cpp
3186 lines (2707 loc) · 106 KB
/
NativeObject.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/. */
#include "vm/NativeObject-inl.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/Casting.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Maybe.h"
#include <algorithm>
#include "debugger/DebugAPI.h"
#include "gc/Marking.h"
#include "gc/MaybeRooted.h"
#include "jit/BaselineIC.h"
#include "js/CharacterEncoding.h"
#include "js/Result.h"
#include "js/Value.h"
#include "util/Memory.h"
#include "vm/EqualityOperations.h" // js::SameValue
#include "vm/TypedArrayObject.h"
#include "gc/Nursery-inl.h"
#include "vm/ArrayObject-inl.h"
#include "vm/BytecodeLocation-inl.h"
#include "vm/EnvironmentObject-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/Shape-inl.h"
#include "vm/TypeInference-inl.h"
using namespace js;
using JS::AutoCheckCannotGC;
using mozilla::ArrayLength;
using mozilla::CheckedInt;
using mozilla::DebugOnly;
using mozilla::PodCopy;
using mozilla::RoundUpPow2;
struct EmptyObjectElements {
const ObjectElements emptyElementsHeader;
// Add an extra (unused) Value to make sure an out-of-bounds index when
// masked (resulting in index 0) accesses valid memory.
const Value val;
public:
constexpr EmptyObjectElements()
: emptyElementsHeader(0, 0), val(UndefinedValue()) {}
explicit constexpr EmptyObjectElements(ObjectElements::SharedMemory shmem)
: emptyElementsHeader(0, 0, shmem), val(UndefinedValue()) {}
};
static constexpr EmptyObjectElements emptyElementsHeader;
/* Objects with no elements share one empty set of elements. */
HeapSlot* const js::emptyObjectElements = reinterpret_cast<HeapSlot*>(
uintptr_t(&emptyElementsHeader) + sizeof(ObjectElements));
static constexpr EmptyObjectElements emptyElementsHeaderShared(
ObjectElements::SharedMemory::IsShared);
/* Objects with no elements share one empty set of elements. */
HeapSlot* const js::emptyObjectElementsShared = reinterpret_cast<HeapSlot*>(
uintptr_t(&emptyElementsHeaderShared) + sizeof(ObjectElements));
#ifdef DEBUG
bool NativeObject::canHaveNonEmptyElements() {
return !this->is<TypedArrayObject>();
}
#endif // DEBUG
/* static */
void ObjectElements::ConvertElementsToDoubles(JSContext* cx,
uintptr_t elementsPtr) {
/*
* This function has an otherwise unused JSContext argument so that it can
* be called directly from Ion code. Only arrays can have their dense
* elements converted to doubles, and arrays never have empty elements.
*/
HeapSlot* elementsHeapPtr = (HeapSlot*)elementsPtr;
MOZ_ASSERT(elementsHeapPtr != emptyObjectElements &&
elementsHeapPtr != emptyObjectElementsShared);
ObjectElements* header = ObjectElements::fromElements(elementsHeapPtr);
MOZ_ASSERT(!header->shouldConvertDoubleElements());
// Note: the elements can be mutated in place even for copy on write
// arrays. See comment on ObjectElements.
Value* vp = (Value*)elementsPtr;
for (size_t i = 0; i < header->initializedLength; i++) {
if (vp[i].isInt32()) {
vp[i].setDouble(vp[i].toInt32());
}
}
header->setShouldConvertDoubleElements();
}
/* static */
bool ObjectElements::MakeElementsCopyOnWrite(JSContext* cx, NativeObject* obj) {
static_assert(sizeof(HeapSlot) >= sizeof(GCPtrObject),
"there must be enough room for the owner object pointer at "
"the end of the elements");
if (!obj->ensureElements(cx, obj->getDenseInitializedLength() + 1)) {
return false;
}
ObjectElements* header = obj->getElementsHeader();
// Note: this method doesn't update type information to indicate that the
// elements might be copy on write. Handling this is left to the caller.
MOZ_ASSERT(!header->isCopyOnWrite());
MOZ_ASSERT(obj->isExtensible());
header->flags |= COPY_ON_WRITE;
header->ownerObject().init(obj);
return true;
}
/* static */
bool ObjectElements::PreventExtensions(JSContext* cx, NativeObject* obj) {
if (!obj->maybeCopyElementsForWrite(cx)) {
return false;
}
if (!obj->hasEmptyElements()) {
obj->shrinkCapacityToInitializedLength(cx);
MarkObjectGroupFlags(cx, obj, OBJECT_FLAG_NON_EXTENSIBLE_ELEMENTS);
}
// shrinkCapacityToInitializedLength ensures there are no shifted elements.
MOZ_ASSERT(obj->getElementsHeader()->numShiftedElements() == 0);
return true;
}
/* static */
void ObjectElements::FreezeOrSeal(JSContext* cx, NativeObject* obj,
IntegrityLevel level) {
MOZ_ASSERT_IF(level == IntegrityLevel::Frozen && obj->is<ArrayObject>(),
!obj->as<ArrayObject>().lengthIsWritable());
MOZ_ASSERT(!obj->denseElementsAreCopyOnWrite());
MOZ_ASSERT(!obj->isExtensible());
MOZ_ASSERT(obj->getElementsHeader()->numShiftedElements() == 0);
if (obj->hasEmptyElements() || obj->denseElementsAreFrozen()) {
return;
}
if (!obj->denseElementsAreSealed()) {
obj->getElementsHeader()->seal();
}
if (level == IntegrityLevel::Frozen) {
obj->getElementsHeader()->freeze();
}
}
#ifdef DEBUG
static mozilla::Atomic<bool, mozilla::Relaxed> gShapeConsistencyChecksEnabled(
false);
/* static */
void js::NativeObject::enableShapeConsistencyChecks() {
gShapeConsistencyChecksEnabled = true;
}
void js::NativeObject::checkShapeConsistency() {
if (!gShapeConsistencyChecksEnabled) {
return;
}
MOZ_ASSERT(isNative());
Shape* shape = lastProperty();
Shape* prev = nullptr;
AutoCheckCannotGC nogc;
if (inDictionaryMode()) {
if (ShapeTable* table = shape->maybeTable(nogc)) {
for (uint32_t fslot = table->freeList(); fslot != SHAPE_INVALID_SLOT;
fslot = getSlot(fslot).toPrivateUint32()) {
MOZ_ASSERT(fslot < slotSpan());
}
while (shape->parent) {
MOZ_ASSERT_IF(lastProperty() != shape, !shape->hasTable());
ShapeTable::Entry& entry =
table->search<MaybeAdding::NotAdding>(shape->propid(), nogc);
MOZ_ASSERT(entry.shape() == shape);
shape = shape->parent;
}
}
shape = lastProperty();
while (shape) {
MOZ_ASSERT_IF(!shape->isEmptyShape() && shape->isDataProperty(),
shape->slot() < slotSpan());
if (!prev) {
MOZ_ASSERT(lastProperty() == shape);
MOZ_ASSERT(shape->dictNext.toObject() == this);
} else {
MOZ_ASSERT(shape->dictNext.toShape() == prev);
}
prev = shape;
shape = shape->parent;
}
} else {
while (shape->parent) {
if (ShapeTable* table = shape->maybeTable(nogc)) {
MOZ_ASSERT(shape->parent);
for (Shape::Range<NoGC> r(shape); !r.empty(); r.popFront()) {
ShapeTable::Entry& entry =
table->search<MaybeAdding::NotAdding>(r.front().propid(), nogc);
MOZ_ASSERT(entry.shape() == &r.front());
}
}
if (prev) {
MOZ_ASSERT_IF(shape->isDataProperty(),
prev->maybeSlot() >= shape->maybeSlot());
shape->children.checkHasChild(prev);
}
prev = shape;
shape = shape->parent;
}
}
}
#endif
void js::NativeObject::initializeSlotRange(uint32_t start, uint32_t length) {
/*
* No bounds check, as this is used when the object's shape does not
* reflect its allocated slots (updateSlotsForSpan).
*/
HeapSlot* fixedStart;
HeapSlot* fixedEnd;
HeapSlot* slotsStart;
HeapSlot* slotsEnd;
getSlotRangeUnchecked(start, length, &fixedStart, &fixedEnd, &slotsStart,
&slotsEnd);
uint32_t offset = start;
for (HeapSlot* sp = fixedStart; sp < fixedEnd; sp++) {
sp->init(this, HeapSlot::Slot, offset++, UndefinedValue());
}
for (HeapSlot* sp = slotsStart; sp < slotsEnd; sp++) {
sp->init(this, HeapSlot::Slot, offset++, UndefinedValue());
}
}
void js::NativeObject::initSlotRange(uint32_t start, const Value* vector,
uint32_t length) {
HeapSlot* fixedStart;
HeapSlot* fixedEnd;
HeapSlot* slotsStart;
HeapSlot* slotsEnd;
getSlotRange(start, length, &fixedStart, &fixedEnd, &slotsStart, &slotsEnd);
for (HeapSlot* sp = fixedStart; sp < fixedEnd; sp++) {
sp->init(this, HeapSlot::Slot, start++, *vector++);
}
for (HeapSlot* sp = slotsStart; sp < slotsEnd; sp++) {
sp->init(this, HeapSlot::Slot, start++, *vector++);
}
}
#ifdef DEBUG
bool js::NativeObject::slotInRange(uint32_t slot,
SentinelAllowed sentinel) const {
MOZ_ASSERT(!gc::IsForwarded(lastProperty()));
uint32_t capacity = numFixedSlots() + numDynamicSlots();
if (sentinel == SENTINEL_ALLOWED) {
return slot <= capacity;
}
return slot < capacity;
}
bool js::NativeObject::slotIsFixed(uint32_t slot) const {
// We call numFixedSlotsMaybeForwarded() to allow reading slots of
// associated objects in trace hooks that may be called during a moving GC.
return slot < numFixedSlotsMaybeForwarded();
}
bool js::NativeObject::isNumFixedSlots(uint32_t nfixed) const {
// We call numFixedSlotsMaybeForwarded() to allow reading slots of
// associated objects in trace hooks that may be called during a moving GC.
return nfixed == numFixedSlotsMaybeForwarded();
}
#endif /* DEBUG */
Shape* js::NativeObject::lookup(JSContext* cx, jsid id) {
MOZ_ASSERT(isNative());
return Shape::search(cx, lastProperty(), id);
}
Shape* js::NativeObject::lookupPure(jsid id) {
MOZ_ASSERT(isNative());
return Shape::searchNoHashify(lastProperty(), id);
}
void NativeObject::setLastPropertyShrinkFixedSlots(Shape* shape) {
MOZ_ASSERT(!inDictionaryMode());
MOZ_ASSERT(!shape->inDictionary());
MOZ_ASSERT(shape->zone() == zone());
MOZ_ASSERT(lastProperty()->slotSpan() == shape->slotSpan());
MOZ_ASSERT(shape->getObjectClass() == getClass());
DebugOnly<size_t> oldFixed = numFixedSlots();
DebugOnly<size_t> newFixed = shape->numFixedSlots();
MOZ_ASSERT(newFixed < oldFixed);
MOZ_ASSERT(shape->slotSpan() <= oldFixed);
MOZ_ASSERT(shape->slotSpan() <= newFixed);
MOZ_ASSERT(dynamicSlotsCount(oldFixed, shape->slotSpan(), getClass()) == 0);
MOZ_ASSERT(dynamicSlotsCount(newFixed, shape->slotSpan(), getClass()) == 0);
setShape(shape);
}
bool NativeObject::setSlotSpan(JSContext* cx, uint32_t span) {
MOZ_ASSERT(inDictionaryMode());
size_t oldSpan = lastProperty()->base()->slotSpan();
if (oldSpan == span) {
return true;
}
if (!updateSlotsForSpan(cx, oldSpan, span)) {
return false;
}
lastProperty()->base()->setSlotSpan(span);
return true;
}
bool NativeObject::growSlots(JSContext* cx, uint32_t oldCount,
uint32_t newCount) {
MOZ_ASSERT(newCount > oldCount);
MOZ_ASSERT_IF(!is<ArrayObject>(), newCount >= SLOT_CAPACITY_MIN);
/*
* Slot capacities are determined by the span of allocated objects. Due to
* the limited number of bits to store shape slots, object growth is
* throttled well before the slot capacity can overflow.
*/
NativeObject::slotsSizeMustNotOverflow();
MOZ_ASSERT(newCount <= MAX_SLOTS_COUNT);
if (!oldCount) {
MOZ_ASSERT(!slots_);
slots_ = AllocateObjectBuffer<HeapSlot>(cx, this, newCount);
if (!slots_) {
return false;
}
Debug_SetSlotRangeToCrashOnTouch(slots_, newCount);
AddCellMemory(this, newCount * sizeof(HeapSlot), MemoryUse::ObjectSlots);
return true;
}
HeapSlot* newslots =
ReallocateObjectBuffer<HeapSlot>(cx, this, slots_, oldCount, newCount);
if (!newslots) {
return false; /* Leave slots at its old size. */
}
RemoveCellMemory(this, oldCount * sizeof(HeapSlot), MemoryUse::ObjectSlots);
AddCellMemory(this, newCount * sizeof(HeapSlot), MemoryUse::ObjectSlots);
slots_ = newslots;
Debug_SetSlotRangeToCrashOnTouch(slots_ + oldCount, newCount - oldCount);
return true;
}
/* static */
bool NativeObject::growSlotsPure(JSContext* cx, NativeObject* obj,
uint32_t newCount) {
// IC code calls this directly.
AutoUnsafeCallWithABI unsafe;
if (!obj->growSlots(cx, obj->numDynamicSlots(), newCount)) {
cx->recoverFromOutOfMemory();
return false;
}
return true;
}
/* static */
bool NativeObject::addDenseElementPure(JSContext* cx, NativeObject* obj) {
// IC code calls this directly.
AutoUnsafeCallWithABI unsafe;
MOZ_ASSERT(obj->getDenseInitializedLength() == obj->getDenseCapacity());
MOZ_ASSERT(!obj->denseElementsAreCopyOnWrite());
MOZ_ASSERT(obj->isExtensible());
MOZ_ASSERT(!obj->isIndexed());
MOZ_ASSERT(!obj->is<TypedArrayObject>());
MOZ_ASSERT_IF(obj->is<ArrayObject>(),
obj->as<ArrayObject>().lengthIsWritable());
// growElements will report OOM also if the number of dense elements will
// exceed MAX_DENSE_ELEMENTS_COUNT. See goodElementsAllocationAmount.
uint32_t oldCapacity = obj->getDenseCapacity();
if (MOZ_UNLIKELY(!obj->growElements(cx, oldCapacity + 1))) {
cx->recoverFromOutOfMemory();
return false;
}
MOZ_ASSERT(obj->getDenseCapacity() > oldCapacity);
MOZ_ASSERT(obj->getDenseCapacity() <= MAX_DENSE_ELEMENTS_COUNT);
return true;
}
static inline void FreeSlots(JSContext* cx, NativeObject* obj,
HeapSlot* slots) {
if (cx->isHelperThreadContext()) {
js_free(slots);
} else if (obj->isTenured()) {
MOZ_ASSERT(!cx->nursery().isInside(slots));
js_free(slots);
} else {
cx->nursery().freeBuffer(slots);
}
}
void NativeObject::shrinkSlots(JSContext* cx, uint32_t oldCount,
uint32_t newCount) {
MOZ_ASSERT(newCount < oldCount);
if (newCount == 0) {
RemoveCellMemory(this, numDynamicSlots() * sizeof(HeapSlot),
MemoryUse::ObjectSlots);
FreeSlots(cx, this, slots_);
slots_ = nullptr;
return;
}
MOZ_ASSERT_IF(!is<ArrayObject>(), newCount >= SLOT_CAPACITY_MIN);
// Update the memory tracking whether or not the reallocation succeeds,
// because we have no way to tell the buffer size if it fails.
RemoveCellMemory(this, oldCount * sizeof(HeapSlot), MemoryUse::ObjectSlots);
AddCellMemory(this, newCount * sizeof(HeapSlot), MemoryUse::ObjectSlots);
HeapSlot* newslots =
ReallocateObjectBuffer<HeapSlot>(cx, this, slots_, oldCount, newCount);
if (!newslots) {
cx->recoverFromOutOfMemory();
return; // Leave slots at its old size.
}
slots_ = newslots;
}
bool NativeObject::willBeSparseElements(uint32_t requiredCapacity,
uint32_t newElementsHint) {
MOZ_ASSERT(isNative());
MOZ_ASSERT(requiredCapacity > MIN_SPARSE_INDEX);
uint32_t cap = getDenseCapacity();
MOZ_ASSERT(requiredCapacity >= cap);
if (requiredCapacity > MAX_DENSE_ELEMENTS_COUNT) {
return true;
}
uint32_t minimalDenseCount = requiredCapacity / SPARSE_DENSITY_RATIO;
if (newElementsHint >= minimalDenseCount) {
return false;
}
minimalDenseCount -= newElementsHint;
if (minimalDenseCount > cap) {
return true;
}
uint32_t len = getDenseInitializedLength();
const Value* elems = getDenseElements();
for (uint32_t i = 0; i < len; i++) {
if (!elems[i].isMagic(JS_ELEMENTS_HOLE) && !--minimalDenseCount) {
return false;
}
}
return true;
}
/* static */
DenseElementResult NativeObject::maybeDensifySparseElements(
JSContext* cx, HandleNativeObject obj) {
/*
* Wait until after the object goes into dictionary mode, which must happen
* when sparsely packing any array with more than MIN_SPARSE_INDEX elements
* (see PropertyTree::MAX_HEIGHT).
*/
if (!obj->inDictionaryMode()) {
return DenseElementResult::Incomplete;
}
/*
* Only measure the number of indexed properties every log(n) times when
* populating the object.
*/
uint32_t slotSpan = obj->slotSpan();
if (slotSpan != RoundUpPow2(slotSpan)) {
return DenseElementResult::Incomplete;
}
/* Watch for conditions under which an object's elements cannot be dense. */
if (!obj->isExtensible()) {
return DenseElementResult::Incomplete;
}
/*
* The indexes in the object need to be sufficiently dense before they can
* be converted to dense mode.
*/
uint32_t numDenseElements = 0;
uint32_t newInitializedLength = 0;
RootedShape shape(cx, obj->lastProperty());
while (!shape->isEmptyShape()) {
uint32_t index;
if (IdIsIndex(shape->propid(), &index)) {
if (shape->attributes() == JSPROP_ENUMERATE &&
shape->hasDefaultGetter() && shape->hasDefaultSetter()) {
numDenseElements++;
newInitializedLength = std::max(newInitializedLength, index + 1);
} else {
/*
* For simplicity, only densify the object if all indexed
* properties can be converted to dense elements.
*/
return DenseElementResult::Incomplete;
}
}
shape = shape->previous();
}
if (numDenseElements * SPARSE_DENSITY_RATIO < newInitializedLength) {
return DenseElementResult::Incomplete;
}
if (newInitializedLength > MAX_DENSE_ELEMENTS_COUNT) {
return DenseElementResult::Incomplete;
}
/*
* This object meets all necessary restrictions, convert all indexed
* properties into dense elements.
*/
if (!obj->maybeCopyElementsForWrite(cx)) {
return DenseElementResult::Failure;
}
if (newInitializedLength > obj->getDenseCapacity()) {
if (!obj->growElements(cx, newInitializedLength)) {
return DenseElementResult::Failure;
}
}
obj->ensureDenseInitializedLength(cx, newInitializedLength, 0);
RootedValue value(cx);
shape = obj->lastProperty();
while (!shape->isEmptyShape()) {
jsid id = shape->propid();
uint32_t index;
if (IdIsIndex(id, &index)) {
value = obj->getSlot(shape->slot());
/*
* When removing a property from a dictionary, the specified
* property will be removed from the dictionary list and the
* last property will then be changed due to reshaping the object.
* Compute the next shape in the traverse, watching for such
* removals from the list.
*/
if (shape != obj->lastProperty()) {
shape = shape->previous();
if (!NativeObject::removeProperty(cx, obj, id)) {
return DenseElementResult::Failure;
}
} else {
if (!NativeObject::removeProperty(cx, obj, id)) {
return DenseElementResult::Failure;
}
shape = obj->lastProperty();
}
obj->setDenseElement(index, value);
} else {
shape = shape->previous();
}
}
/*
* All indexed properties on the object are now dense, clear the indexed
* flag so that we will not start using sparse indexes again if we need
* to grow the object.
*/
if (!NativeObject::clearFlag(cx, obj, BaseShape::INDEXED)) {
return DenseElementResult::Failure;
}
return DenseElementResult::Success;
}
void NativeObject::moveShiftedElements() {
MOZ_ASSERT(isExtensible());
ObjectElements* header = getElementsHeader();
uint32_t numShifted = header->numShiftedElements();
MOZ_ASSERT(numShifted > 0);
uint32_t initLength = header->initializedLength;
ObjectElements* newHeader =
static_cast<ObjectElements*>(getUnshiftedElementsHeader());
memmove(newHeader, header, sizeof(ObjectElements));
newHeader->clearShiftedElements();
newHeader->capacity += numShifted;
elements_ = newHeader->elements();
// To move the elements, temporarily update initializedLength to include
// the shifted elements.
newHeader->initializedLength += numShifted;
// Move the elements. Initialize to |undefined| to ensure pre-barriers
// don't see garbage.
for (size_t i = 0; i < numShifted; i++) {
initDenseElement(i, UndefinedValue());
}
moveDenseElements(0, numShifted, initLength);
// Restore the initialized length. We use setDenseInitializedLength to
// make sure prepareElementRangeForOverwrite is called on the shifted
// elements.
setDenseInitializedLength(initLength);
}
void NativeObject::maybeMoveShiftedElements() {
MOZ_ASSERT(isExtensible());
ObjectElements* header = getElementsHeader();
MOZ_ASSERT(header->numShiftedElements() > 0);
// Move the elements if less than a third of the allocated space is in use.
if (header->capacity < header->numAllocatedElements() / 3) {
moveShiftedElements();
}
}
bool NativeObject::tryUnshiftDenseElements(uint32_t count) {
MOZ_ASSERT(isExtensible());
MOZ_ASSERT(count > 0);
ObjectElements* header = getElementsHeader();
uint32_t numShifted = header->numShiftedElements();
if (count > numShifted) {
// We need more elements than are easily available. Try to make space
// for more elements than we need (and shift the remaining ones) so
// that unshifting more elements later will be fast.
// Don't bother reserving elements if the number of elements is small.
// Note that there's no technical reason for using this particular
// limit.
if (header->initializedLength <= 10 || header->isCopyOnWrite() ||
header->hasNonwritableArrayLength() ||
MOZ_UNLIKELY(count > ObjectElements::MaxShiftedElements)) {
return false;
}
MOZ_ASSERT(header->capacity >= header->initializedLength);
uint32_t unusedCapacity = header->capacity - header->initializedLength;
// Determine toShift, the number of extra elements we want to make
// available.
uint32_t toShift = count - numShifted;
MOZ_ASSERT(toShift <= ObjectElements::MaxShiftedElements,
"count <= MaxShiftedElements so toShift <= MaxShiftedElements");
// Give up if we need to allocate more elements.
if (toShift > unusedCapacity) {
return false;
}
// Move more elements than we need, so that other unshift calls will be
// fast. We just have to make sure we don't exceed unusedCapacity.
toShift = std::min(toShift + unusedCapacity / 2, unusedCapacity);
// Ensure |numShifted + toShift| does not exceed MaxShiftedElements.
if (numShifted + toShift > ObjectElements::MaxShiftedElements) {
toShift = ObjectElements::MaxShiftedElements - numShifted;
}
MOZ_ASSERT(count <= numShifted + toShift);
MOZ_ASSERT(numShifted + toShift <= ObjectElements::MaxShiftedElements);
MOZ_ASSERT(toShift <= unusedCapacity);
// Now move/unshift the elements.
uint32_t initLen = header->initializedLength;
setDenseInitializedLength(initLen + toShift);
for (uint32_t i = 0; i < toShift; i++) {
initDenseElement(initLen + i, UndefinedValue());
}
moveDenseElements(toShift, 0, initLen);
// Shift the elements we just prepended.
shiftDenseElementsUnchecked(toShift);
// We can now fall-through to the fast path below.
header = getElementsHeader();
MOZ_ASSERT(header->numShiftedElements() == numShifted + toShift);
numShifted = header->numShiftedElements();
MOZ_ASSERT(count <= numShifted);
}
elements_ -= count;
ObjectElements* newHeader = getElementsHeader();
memmove(newHeader, header, sizeof(ObjectElements));
newHeader->unshiftShiftedElements(count);
// Initialize to |undefined| to ensure pre-barriers don't see garbage.
for (uint32_t i = 0; i < count; i++) {
initDenseElement(i, UndefinedValue());
}
return true;
}
// Given a requested capacity (in elements) and (potentially) the length of an
// array for which elements are being allocated, compute an actual allocation
// amount (in elements). (Allocation amounts include space for an
// ObjectElements instance, so a return value of |N| implies
// |N - ObjectElements::VALUES_PER_HEADER| usable elements.)
//
// The requested/actual allocation distinction is meant to:
//
// * preserve amortized O(N) time to add N elements;
// * minimize the number of unused elements beyond an array's length, and
// * provide at least SLOT_CAPACITY_MIN elements no matter what (so adding
// the first several elements to small arrays only needs one allocation).
//
// Note: the structure and behavior of this method follow along with
// UnboxedArrayObject::chooseCapacityIndex. Changes to the allocation strategy
// in one should generally be matched by the other.
/* static */
bool NativeObject::goodElementsAllocationAmount(JSContext* cx,
uint32_t reqCapacity,
uint32_t length,
uint32_t* goodAmount) {
if (reqCapacity > MAX_DENSE_ELEMENTS_COUNT) {
ReportOutOfMemory(cx);
return false;
}
uint32_t reqAllocated = reqCapacity + ObjectElements::VALUES_PER_HEADER;
// Handle "small" requests primarily by doubling.
const uint32_t Mebi = 1 << 20;
if (reqAllocated < Mebi) {
uint32_t amount =
mozilla::AssertedCast<uint32_t>(RoundUpPow2(reqAllocated));
// If |amount| would be 2/3 or more of the array's length, adjust
// it (up or down) to be equal to the array's length. This avoids
// allocating excess elements that aren't likely to be needed, either
// in this resizing or a subsequent one. The 2/3 factor is chosen so
// that exceptional resizings will at most triple the capacity, as
// opposed to the usual doubling.
uint32_t goodCapacity = amount - ObjectElements::VALUES_PER_HEADER;
if (length >= reqCapacity && goodCapacity > (length / 3) * 2) {
amount = length + ObjectElements::VALUES_PER_HEADER;
}
if (amount < SLOT_CAPACITY_MIN) {
amount = SLOT_CAPACITY_MIN;
}
*goodAmount = amount;
return true;
}
// The almost-doubling above wastes a lot of space for larger bucket sizes.
// For large amounts, switch to bucket sizes that obey this formula:
//
// count(n+1) = Math.ceil(count(n) * 1.125)
//
// where |count(n)| is the size of the nth bucket, measured in 2**20 slots.
// These bucket sizes still preserve amortized O(N) time to add N elements,
// just with a larger constant factor.
//
// The bucket size table below was generated with this JavaScript (and
// manual reformatting):
//
// for (let n = 1, i = 0; i < 34; i++) {
// print('0x' + (n * (1 << 20)).toString(16) + ', ');
// n = Math.ceil(n * 1.125);
// }
static const uint32_t BigBuckets[] = {
0x100000, 0x200000, 0x300000, 0x400000, 0x500000, 0x600000,
0x700000, 0x800000, 0x900000, 0xb00000, 0xd00000, 0xf00000,
0x1100000, 0x1400000, 0x1700000, 0x1a00000, 0x1e00000, 0x2200000,
0x2700000, 0x2c00000, 0x3200000, 0x3900000, 0x4100000, 0x4a00000,
0x5400000, 0x5f00000, 0x6b00000, 0x7900000, 0x8900000, 0x9b00000,
0xaf00000, 0xc500000, 0xde00000, 0xfa00000};
MOZ_ASSERT(BigBuckets[ArrayLength(BigBuckets) - 1] <=
MAX_DENSE_ELEMENTS_ALLOCATION);
// Pick the first bucket that'll fit |reqAllocated|.
for (uint32_t b : BigBuckets) {
if (b >= reqAllocated) {
*goodAmount = b;
return true;
}
}
// Otherwise, return the maximum bucket size.
*goodAmount = MAX_DENSE_ELEMENTS_ALLOCATION;
return true;
}
bool NativeObject::growElements(JSContext* cx, uint32_t reqCapacity) {
MOZ_ASSERT(isExtensible());
MOZ_ASSERT(canHaveNonEmptyElements());
if (denseElementsAreCopyOnWrite()) {
MOZ_CRASH();
}
// If there are shifted elements, consider moving them first. If we don't
// move them here, the code below will include the shifted elements in the
// resize.
uint32_t numShifted = getElementsHeader()->numShiftedElements();
if (numShifted > 0) {
// If the number of elements is small, it's cheaper to just move them as
// it may avoid a malloc/realloc. Note that there's no technical reason
// for using this particular value, but it works well in real-world use
// cases.
static const size_t MaxElementsToMoveEagerly = 20;
if (getElementsHeader()->initializedLength <= MaxElementsToMoveEagerly) {
moveShiftedElements();
} else {
maybeMoveShiftedElements();
}
if (getDenseCapacity() >= reqCapacity) {
return true;
}
numShifted = getElementsHeader()->numShiftedElements();
// If |reqCapacity + numShifted| overflows, we just move all shifted
// elements to avoid the problem.
CheckedInt<uint32_t> checkedReqCapacity(reqCapacity);
checkedReqCapacity += numShifted;
if (MOZ_UNLIKELY(!checkedReqCapacity.isValid())) {
moveShiftedElements();
numShifted = 0;
}
}
uint32_t oldCapacity = getDenseCapacity();
MOZ_ASSERT(oldCapacity < reqCapacity);
uint32_t newAllocated = 0;
if (is<ArrayObject>() && !as<ArrayObject>().lengthIsWritable()) {
MOZ_ASSERT(reqCapacity <= as<ArrayObject>().length());
MOZ_ASSERT(reqCapacity <= MAX_DENSE_ELEMENTS_COUNT);
// Preserve the |capacity <= length| invariant for arrays with
// non-writable length. See also js::ArraySetLength which initially
// enforces this requirement.
newAllocated = reqCapacity + numShifted + ObjectElements::VALUES_PER_HEADER;
} else {
if (!goodElementsAllocationAmount(cx, reqCapacity + numShifted,
getElementsHeader()->length,
&newAllocated)) {
return false;
}
}
uint32_t newCapacity =
newAllocated - ObjectElements::VALUES_PER_HEADER - numShifted;
MOZ_ASSERT(newCapacity > oldCapacity && newCapacity >= reqCapacity);
// If newCapacity exceeds MAX_DENSE_ELEMENTS_COUNT, the array should become
// sparse.
MOZ_ASSERT(newCapacity <= MAX_DENSE_ELEMENTS_COUNT);
uint32_t initlen = getDenseInitializedLength();
HeapSlot* oldHeaderSlots =
reinterpret_cast<HeapSlot*>(getUnshiftedElementsHeader());
HeapSlot* newHeaderSlots;
uint32_t oldAllocated = 0;
if (hasDynamicElements()) {
MOZ_ASSERT(oldCapacity <= MAX_DENSE_ELEMENTS_COUNT);
oldAllocated = oldCapacity + ObjectElements::VALUES_PER_HEADER + numShifted;
newHeaderSlots = ReallocateObjectBuffer<HeapSlot>(
cx, this, oldHeaderSlots, oldAllocated, newAllocated);
if (!newHeaderSlots) {
return false; // Leave elements at its old size.
}
} else {
newHeaderSlots = AllocateObjectBuffer<HeapSlot>(cx, this, newAllocated);
if (!newHeaderSlots) {
return false; // Leave elements at its old size.
}
PodCopy(newHeaderSlots, oldHeaderSlots,
ObjectElements::VALUES_PER_HEADER + initlen + numShifted);
}
if (oldAllocated) {
RemoveCellMemory(this, oldAllocated * sizeof(HeapSlot),
MemoryUse::ObjectElements);
}
ObjectElements* newheader = reinterpret_cast<ObjectElements*>(newHeaderSlots);
elements_ = newheader->elements() + numShifted;
getElementsHeader()->capacity = newCapacity;
Debug_SetSlotRangeToCrashOnTouch(elements_ + initlen, newCapacity - initlen);
AddCellMemory(this, newAllocated * sizeof(HeapSlot),
MemoryUse::ObjectElements);
return true;
}
void NativeObject::shrinkElements(JSContext* cx, uint32_t reqCapacity) {
MOZ_ASSERT(canHaveNonEmptyElements());
MOZ_ASSERT(reqCapacity >= getDenseInitializedLength());
if (denseElementsAreCopyOnWrite()) {
MOZ_CRASH();
}
if (!hasDynamicElements()) {
return;
}
// If we have shifted elements, consider moving them.
uint32_t numShifted = getElementsHeader()->numShiftedElements();
if (numShifted > 0) {
maybeMoveShiftedElements();
numShifted = getElementsHeader()->numShiftedElements();
}
uint32_t oldCapacity = getDenseCapacity();
MOZ_ASSERT(reqCapacity < oldCapacity);
uint32_t newAllocated = 0;
MOZ_ALWAYS_TRUE(goodElementsAllocationAmount(cx, reqCapacity + numShifted, 0,
&newAllocated));
MOZ_ASSERT(oldCapacity <= MAX_DENSE_ELEMENTS_COUNT);
uint32_t oldAllocated =
oldCapacity + ObjectElements::VALUES_PER_HEADER + numShifted;
if (newAllocated == oldAllocated) {
return; // Leave elements at its old size.
}
MOZ_ASSERT(newAllocated > ObjectElements::VALUES_PER_HEADER);
uint32_t newCapacity =
newAllocated - ObjectElements::VALUES_PER_HEADER - numShifted;
MOZ_ASSERT(newCapacity <= MAX_DENSE_ELEMENTS_COUNT);
HeapSlot* oldHeaderSlots =
reinterpret_cast<HeapSlot*>(getUnshiftedElementsHeader());
HeapSlot* newHeaderSlots = ReallocateObjectBuffer<HeapSlot>(
cx, this, oldHeaderSlots, oldAllocated, newAllocated);
if (!newHeaderSlots) {
cx->recoverFromOutOfMemory();
return; // Leave elements at its old size.
}
RemoveCellMemory(this, oldAllocated * sizeof(HeapSlot),
MemoryUse::ObjectElements);
ObjectElements* newheader = reinterpret_cast<ObjectElements*>(newHeaderSlots);
elements_ = newheader->elements() + numShifted;