Debian Codegraph @

js/src/vm/NativeObject.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "vm/NativeObject-inl.h"
8
9 #include "mozilla/Casting.h"
10 #include "mozilla/CheckedInt.h"
11 #include "mozilla/Maybe.h"
12
13 #include <algorithm>
14 #include <iterator>
15
16 #include "gc/MaybeRooted.h"
17 #include "gc/StableCellHasher.h"
18 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
19 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
20 #include "js/Printer.h" // js::GenericPrinter
21 #include "js/Value.h"
22 #include "vm/EqualityOperations.h" // js::SameValue
23 #include "vm/GetterSetter.h" // js::GetterSetter
24 #include "vm/Interpreter.h" // js::CallGetter, js::CallSetter
25 #include "vm/JSONPrinter.h" // js::JSONPrinter
26 #include "vm/PlainObject.h" // js::PlainObject
27 #include "vm/TypedArrayObject.h"
28 #include "vm/Watchtower.h"
29 #include "gc/Nursery-inl.h"
30 #include "vm/JSObject-inl.h"
31 #include "vm/Shape-inl.h"
32
33 using namespace js;
34
35 using mozilla::CheckedInt;
36 using mozilla::PodCopy;
37 using mozilla::RoundUpPow2;
38
39 struct EmptyObjectElements {
40 const ObjectElements emptyElementsHeader;
41
42 // Add an extra (unused) Value to make sure an out-of-bounds index when
43 // masked (resulting in index 0) accesses valid memory.
44 const Value val;
45
46 public:
47 constexpr EmptyObjectElements()
48 : emptyElementsHeader(0, 0), val(UndefinedValue()) {}
49 explicit constexpr EmptyObjectElements(ObjectElements::SharedMemory shmem)
50 : emptyElementsHeader(0, 0, shmem), val(UndefinedValue()) {}
51 };
52
53 static constexpr EmptyObjectElements emptyElementsHeader;
54
55 /* Objects with no elements share one empty set of elements. */
56 HeapSlot* const js::emptyObjectElements = reinterpret_cast<HeapSlot*>(
57 uintptr_t(&emptyElementsHeader) + sizeof(ObjectElements));
58
59 static constexpr EmptyObjectElements emptyElementsHeaderShared(
60 ObjectElements::SharedMemory::IsShared);
61
62 /* Objects with no elements share one empty set of elements. */
63 HeapSlot* const js::emptyObjectElementsShared = reinterpret_cast<HeapSlot*>(
64 uintptr_t(&emptyElementsHeaderShared) + sizeof(ObjectElements));
65
66 struct EmptyObjectSlots : public ObjectSlots {
67 explicit constexpr EmptyObjectSlots(size_t dictionarySlotSpan)
68 : ObjectSlots(0, dictionarySlotSpan, NoUniqueIdInSharedEmptySlots) {}
69 };
70
71 static constexpr EmptyObjectSlots emptyObjectSlotsHeaders[17] = {
72 EmptyObjectSlots(0), EmptyObjectSlots(1), EmptyObjectSlots(2),
73 EmptyObjectSlots(3), EmptyObjectSlots(4), EmptyObjectSlots(5),
74 EmptyObjectSlots(6), EmptyObjectSlots(7), EmptyObjectSlots(8),
75 EmptyObjectSlots(9), EmptyObjectSlots(10), EmptyObjectSlots(11),
76 EmptyObjectSlots(12), EmptyObjectSlots(13), EmptyObjectSlots(14),
77 EmptyObjectSlots(15), EmptyObjectSlots(16)};
78
79 static_assert(std::size(emptyObjectSlotsHeaders) ==
80 NativeObject::MAX_FIXED_SLOTS + 1);
81
82 MOZ_RUNINIT HeapSlot* const js::emptyObjectSlotsForDictionaryObject[17] = {
83 emptyObjectSlotsHeaders[0].slots(), emptyObjectSlotsHeaders[1].slots(),
84 emptyObjectSlotsHeaders[2].slots(), emptyObjectSlotsHeaders[3].slots(),
85 emptyObjectSlotsHeaders[4].slots(), emptyObjectSlotsHeaders[5].slots(),
86 emptyObjectSlotsHeaders[6].slots(), emptyObjectSlotsHeaders[7].slots(),
87 emptyObjectSlotsHeaders[8].slots(), emptyObjectSlotsHeaders[9].slots(),
88 emptyObjectSlotsHeaders[10].slots(), emptyObjectSlotsHeaders[11].slots(),
89 emptyObjectSlotsHeaders[12].slots(), emptyObjectSlotsHeaders[13].slots(),
90 emptyObjectSlotsHeaders[14].slots(), emptyObjectSlotsHeaders[15].slots(),
91 emptyObjectSlotsHeaders[16].slots()};
92
93 static_assert(std::size(emptyObjectSlotsForDictionaryObject) ==
94 NativeObject::MAX_FIXED_SLOTS + 1);
95
96 MOZ_RUNINIT HeapSlot* const js::emptyObjectSlots =
97 emptyObjectSlotsForDictionaryObject[0];
98
99 #ifdef DEBUG
100
101 bool NativeObject::canHaveNonEmptyElements() {
102 return !this->is<TypedArrayObject>();
103 }
104
105 #endif // DEBUG
106
107 /* static */
108 void ObjectElements::PrepareForPreventExtensions(JSContext* cx,
109 NativeObject* obj) {
110 if (!obj->hasEmptyElements()) {
111 obj->shrinkCapacityToInitializedLength(cx);
112 }
113
114 // shrinkCapacityToInitializedLength ensures there are no shifted elements.
115 MOZ_ASSERT(obj->getElementsHeader()->numShiftedElements() == 0);
116 }
117
118 /* static */
119 void ObjectElements::PreventExtensions(NativeObject* obj) {
120 MOZ_ASSERT(!obj->isExtensible());
121 MOZ_ASSERT(obj->getElementsHeader()->numShiftedElements() == 0);
122 MOZ_ASSERT(obj->getDenseInitializedLength() == obj->getDenseCapacity());
123
124 if (!obj->hasEmptyElements()) {
125 obj->getElementsHeader()->setNotExtensible();
126 }
127 }
128
129 /* static */
130 bool ObjectElements::FreezeOrSeal(JSContext* cx, Handle<NativeObject*> obj,
131 IntegrityLevel level) {
132 MOZ_ASSERT_IF(level == IntegrityLevel::Frozen && obj->is<ArrayObject>(),
133 !obj->as<ArrayObject>().lengthIsWritable());
134 MOZ_ASSERT(!obj->isExtensible());
135 MOZ_ASSERT(obj->getElementsHeader()->numShiftedElements() == 0);
136
137 if (obj->hasEmptyElements() || obj->denseElementsAreFrozen()) {
138 return true;
139 }
140
141 if (level == IntegrityLevel::Frozen) {
142 if (!JSObject::setFlag(cx, obj, ObjectFlag::FrozenElements)) {
143 return false;
144 }
145 }
146
147 if (!obj->denseElementsAreSealed()) {
148 obj->getElementsHeader()->seal();
149 }
150
151 if (level == IntegrityLevel::Frozen) {
152 obj->getElementsHeader()->freeze();
153 }
154
155 return true;
156 }
157
158 #if defined(DEBUG) || defined(JS_JITSPEW)
159
160 template <typename KnownF, typename UnknownF>
161 void ForEachObjectElementsFlag(uint16_t flags, KnownF known, UnknownF unknown) {
162 for (uint16_t i = 1; i; i = i << 1) {
163 if (!(flags & i)) {
164 continue;
165 }
166 switch (ObjectElements::Flags(flags & i)) {
167 case ObjectElements::Flags::FIXED:
168 known("FIXED");
169 break;
170 case ObjectElements::Flags::NONWRITABLE_ARRAY_LENGTH:
171 known("NONWRITABLE_ARRAY_LENGTH");
172 break;
173 case ObjectElements::Flags::SHARED_MEMORY:
174 known("SHARED_MEMORY");
175 break;
176 case ObjectElements::Flags::NOT_EXTENSIBLE:
177 known("NOT_EXTENSIBLE");
178 break;
179 case ObjectElements::Flags::SEALED:
180 known("SEALED");
181 break;
182 case ObjectElements::Flags::FROZEN:
183 known("FROZEN");
184 break;
185 case ObjectElements::Flags::NON_PACKED:
186 known("NON_PACKED");
187 break;
188 case ObjectElements::Flags::MAYBE_IN_ITERATION:
189 known("MAYBE_IN_ITERATION");
190 break;
191 default:
192 unknown(i);
193 break;
194 }
195 }
196 }
197
198 void ObjectElements::dumpStringContent(js::GenericPrinter& out) const {
199 out.printf("<(js::ObjectElements*)0x%p, flags=[", this);
200
201 bool first = true;
202 ForEachObjectElementsFlag(
203 flags,
204 [&](const char* name) {
205 if (!first) {
206 out.put(", ");
207 }
208 first = false;
209
210 out.put(name);
211 },
212 [&](uint16_t value) {
213 if (!first) {
214 out.put(", ");
215 }
216 first = false;
217
218 out.printf("Unknown(%04x)", value);
219 });
220 out.put("]");
221
222 out.printf(", init=%u, capacity=%u, length=%u>", initializedLength, capacity,
223 length);
224 }
225 #endif
226
227 #ifdef DEBUG
228 static mozilla::Atomic<bool, mozilla::Relaxed> gShapeConsistencyChecksEnabled(
229 false);
230
231 /* static */
232 void js::NativeObject::enableShapeConsistencyChecks() {
233 gShapeConsistencyChecksEnabled = true;
234 }
235
236 void js::NativeObject::checkShapeConsistency() {
237 if (!gShapeConsistencyChecksEnabled) {
238 return;
239 }
240
241 MOZ_ASSERT(is<NativeObject>());
242
243 if (PropMap* map = shape()->propMap()) {
244 map->checkConsistency(this);
245 } else {
246 MOZ_ASSERT(shape()->propMapLength() == 0);
247 }
248 }
249 #endif
250
251 #ifdef DEBUG
252
253 bool js::NativeObject::slotInRange(uint32_t slot,
254 SentinelAllowed sentinel) const {
255 MOZ_ASSERT(!gc::IsForwarded(shape()));
256 uint32_t capacity = numFixedSlots() + numDynamicSlots();
257 if (sentinel == SENTINEL_ALLOWED) {
258 return slot <= capacity;
259 }
260 return slot < capacity;
261 }
262
263 bool js::NativeObject::slotIsFixed(uint32_t slot) const {
264 // We call numFixedSlotsMaybeForwarded() to allow reading slots of
265 // associated objects in trace hooks that may be called during a moving GC.
266 return slot < numFixedSlotsMaybeForwarded();
267 }
268
269 bool js::NativeObject::isNumFixedSlots(uint32_t nfixed) const {
270 // We call numFixedSlotsMaybeForwarded() to allow reading slots of
271 // associated objects in trace hooks that may be called during a moving GC.
272 return nfixed == numFixedSlotsMaybeForwarded();
273 }
274
275 uint32_t js::NativeObject::outOfLineNumDynamicSlots() const {
276 return numDynamicSlots();
277 }
278 #endif /* DEBUG */
279
280 mozilla::Maybe<PropertyInfo> js::NativeObject::lookup(JSContext* cx, jsid id) {
281 MOZ_ASSERT(is<NativeObject>());
282 uint32_t index;
283 if (PropMap* map = shape()->lookup(cx, id, &index)) {
284 return mozilla::Some(map->getPropertyInfo(index));
285 }
286 return mozilla::Nothing();
287 }
288
289 mozilla::Maybe<PropertyInfo> js::NativeObject::lookupPure(jsid id) {
290 MOZ_ASSERT(is<NativeObject>());
291 uint32_t index;
292 if (PropMap* map = shape()->lookupPure(id, &index)) {
293 return mozilla::Some(map->getPropertyInfo(index));
294 }
295 return mozilla::Nothing();
296 }
297
298 bool NativeObject::setUniqueId(JSRuntime* runtime, uint64_t uid) {
299 MOZ_ASSERT(!hasUniqueId());
300 MOZ_ASSERT(!gc::HasUniqueId(this));
301
302 Nursery& nursery = runtime->gc.nursery();
303 if (!hasDynamicSlots() && !allocateSlots(nursery, 0)) {
304 return false;
305 }
306
307 getSlotsHeader()->setUniqueId(uid);
308 return true;
309 }
310
311 bool NativeObject::setOrUpdateUniqueId(JSContext* cx, uint64_t uid) {
312 if (!hasDynamicSlots() && !allocateSlots(cx->nursery(), 0)) {
313 ReportOutOfMemory(cx);
314 return false;
315 }
316
317 getSlotsHeader()->setUniqueId(uid);
318 return true;
319 }
320
321 bool NativeObject::growSlots(JSContext* cx, uint32_t oldCapacity,
322 uint32_t newCapacity) {
323 MOZ_ASSERT(newCapacity > oldCapacity);
324
325 /*
326 * Slot capacities are determined by the span of allocated objects. Due to
327 * the limited number of bits to store shape slots, object growth is
328 * throttled well before the slot capacity can overflow.
329 */
330 NativeObject::slotsSizeMustNotOverflow();
331 MOZ_ASSERT(newCapacity <= MAX_SLOTS_COUNT);
332
333 if (!hasDynamicSlots()) {
334 if (!allocateSlots(cx->nursery(), newCapacity)) {
335 ReportOutOfMemory(cx);
336 return false;
337 }
338
339 return true;
340 }
341
342 uint64_t uid = maybeUniqueId();
343
344 uint32_t newAllocated = ObjectSlots::allocCount(newCapacity);
345
346 uint32_t dictionarySpan = getSlotsHeader()->dictionarySlotSpan();
347
348 uint32_t oldAllocated = ObjectSlots::allocCount(oldCapacity);
349
350 ObjectSlots* oldHeaderSlots = ObjectSlots::fromSlots(slots_);
351 MOZ_ASSERT(oldHeaderSlots->capacity() == oldCapacity);
352
353 HeapSlot* allocation = ReallocateCellBuffer<HeapSlot>(
354 cx, this, reinterpret_cast<HeapSlot*>(oldHeaderSlots), oldAllocated,
355 newAllocated);
356 if (!allocation) {
357 return false; /* Leave slots at its old size. */
358 }
359
360 auto* newHeaderSlots =
361 new (allocation) ObjectSlots(newCapacity, dictionarySpan, uid);
362 slots_ = newHeaderSlots->slots();
363
364 Debug_SetSlotRangeToCrashOnTouch(slots_ + oldCapacity,
365 newCapacity - oldCapacity);
366
367 MOZ_ASSERT(hasDynamicSlots());
368 return true;
369 }
370
371 bool NativeObject::growSlotsForNewSlot(JSContext* cx, uint32_t numFixed,
372 uint32_t slot) {
373 MOZ_ASSERT(slotSpan() == slot);
374 MOZ_ASSERT(shape()->numFixedSlots() == numFixed);
375 MOZ_ASSERT(slot >= numFixed);
376
377 uint32_t newCapacity = calculateDynamicSlots(numFixed, slot + 1, getClass());
378
379 uint32_t oldCapacity = numDynamicSlots();
380 MOZ_ASSERT(oldCapacity < newCapacity);
381
382 return growSlots(cx, oldCapacity, newCapacity);
383 }
384
385 bool NativeObject::allocateInitialSlots(JSContext* cx, uint32_t capacity) {
386 uint32_t count = ObjectSlots::allocCount(capacity);
387 HeapSlot* allocation = AllocateCellBuffer<HeapSlot>(cx, this, count);
388 if (MOZ_UNLIKELY(!allocation)) {
389 // The new object will be unreachable, but we have to make it safe for
390 // finalization. It can also be observed with dumpHeap().
391 // Give it a dummy shape that has no dynamic slots.
392 setShape(GlobalObject::getEmptyPlainObjectShape(cx));
393 initEmptyDynamicSlots();
394 return false;
395 }
396
397 auto* headerSlots = new (allocation)
398 ObjectSlots(capacity, 0, ObjectSlots::NoUniqueIdInDynamicSlots);
399 slots_ = headerSlots->slots();
400
401 Debug_SetSlotRangeToCrashOnTouch(slots_, capacity);
402
403 MOZ_ASSERT(hasDynamicSlots());
404 return true;
405 }
406
407 bool NativeObject::allocateSlots(Nursery& nursery, uint32_t newCapacity) {
408 MOZ_ASSERT(!hasUniqueId());
409 MOZ_ASSERT(!hasDynamicSlots());
410
411 uint32_t newAllocated = ObjectSlots::allocCount(newCapacity);
412
413 uint32_t dictionarySpan = getSlotsHeader()->dictionarySlotSpan();
414
415 HeapSlot* allocation =
416 AllocateCellBuffer<HeapSlot>(nursery, zone(), this, newAllocated);
417 if (!allocation) {
418 return false;
419 }
420
421 auto* newHeaderSlots = new (allocation) ObjectSlots(
422 newCapacity, dictionarySpan, ObjectSlots::NoUniqueIdInDynamicSlots);
423 slots_ = newHeaderSlots->slots();
424
425 Debug_SetSlotRangeToCrashOnTouch(slots_, newCapacity);
426
427 MOZ_ASSERT(hasDynamicSlots());
428 return true;
429 }
430
431 /* static */
432 bool NativeObject::growSlotsPure(JSContext* cx, NativeObject* obj,
433 uint32_t newCapacity) {
434 // IC code calls this directly.
435 AutoUnsafeCallWithABI unsafe;
436
437 if (!obj->growSlots(cx, obj->numDynamicSlots(), newCapacity)) {
438 cx->recoverFromOutOfMemory();
439 return false;
440 }
441
442 return true;
443 }
444
445 /* static */
446 bool NativeObject::addDenseElementPure(JSContext* cx, NativeObject* obj) {
447 // IC code calls this directly.
448 AutoUnsafeCallWithABI unsafe;
449
450 MOZ_ASSERT(obj->isExtensible());
451 MOZ_ASSERT(!obj->isIndexed());
452 MOZ_ASSERT(!obj->is<TypedArrayObject>());
453 MOZ_ASSERT_IF(obj->is<ArrayObject>(),
454 obj->as<ArrayObject>().lengthIsWritable());
455
456 // growElements will report OOM also if the number of dense elements will
457 // exceed MAX_DENSE_ELEMENTS_COUNT. See goodElementsAllocationAmount.
458 uint32_t oldCapacity = obj->getDenseCapacity();
459 if (MOZ_UNLIKELY(!obj->growElements(cx, oldCapacity + 1))) {
460 cx->recoverFromOutOfMemory();
461 return false;
462 }
463
464 MOZ_ASSERT(obj->getDenseCapacity() > oldCapacity);
465 MOZ_ASSERT(obj->getDenseCapacity() <= MAX_DENSE_ELEMENTS_COUNT);
466 return true;
467 }
468
469 void NativeObject::shrinkSlots(JSContext* cx, uint32_t oldCapacity,
470 uint32_t newCapacity) {
471 MOZ_ASSERT(hasDynamicSlots());
472 MOZ_ASSERT(newCapacity < oldCapacity);
473 MOZ_ASSERT(oldCapacity == getSlotsHeader()->capacity());
474
475 ObjectSlots* oldHeaderSlots = ObjectSlots::fromSlots(slots_);
476 MOZ_ASSERT(oldHeaderSlots->capacity() == oldCapacity);
477
478 uint64_t uid = maybeUniqueId();
479
480 uint32_t oldAllocated = ObjectSlots::allocCount(oldCapacity);
481
482 if (newCapacity == 0 && uid == 0) {
483 if (gc::IsBufferAlloc(oldHeaderSlots)) {
484 gc::FreeBuffer(zone(), oldHeaderSlots);
485 }
486 // dictionarySlotSpan is initialized to the correct value by the callers.
487 setEmptyDynamicSlots(0);
488 return;
489 }
490
491 MOZ_ASSERT_IF(!is<ArrayObject>() && !hasUniqueId(),
492 newCapacity >= SLOT_CAPACITY_MIN);
493
494 uint32_t dictionarySpan = getSlotsHeader()->dictionarySlotSpan();
495
496 uint32_t newAllocated = ObjectSlots::allocCount(newCapacity);
497
498 HeapSlot* allocation = ReallocateCellBuffer<HeapSlot>(
499 cx, this, reinterpret_cast<HeapSlot*>(oldHeaderSlots), oldAllocated,
500 newAllocated);
501 if (!allocation) {
502 // It's possible for realloc to fail when shrinking an allocation. In this
503 // case we continue using the original allocation but still update the
504 // capacity to the new requested capacity, which is smaller than the actual
505 // capacity.
506 cx->recoverFromOutOfMemory();
507 allocation = reinterpret_cast<HeapSlot*>(getSlotsHeader());
508 }
509
510 auto* newHeaderSlots =
511 new (allocation) ObjectSlots(newCapacity, dictionarySpan, uid);
512 slots_ = newHeaderSlots->slots();
513 }
514
515 void NativeObject::initFixedElements(gc::AllocKind kind, uint32_t length) {
516 uint32_t capacity =
517 gc::GetGCKindSlots(kind) - ObjectElements::VALUES_PER_HEADER;
518
519 setFixedElements();
520 new (getElementsHeader()) ObjectElements(capacity, length);
521 getElementsHeader()->flags |= ObjectElements::FIXED;
522
523 MOZ_ASSERT(hasFixedElements());
524 }
525
526 bool NativeObject::willBeSparseElements(uint32_t requiredCapacity,
527 uint32_t newElementsHint) {
528 MOZ_ASSERT(is<NativeObject>());
529 MOZ_ASSERT(requiredCapacity > MIN_SPARSE_INDEX);
530
531 uint32_t cap = getDenseCapacity();
532 MOZ_ASSERT(requiredCapacity >= cap);
533
534 if (requiredCapacity > MAX_DENSE_ELEMENTS_COUNT) {
535 return true;
536 }
537
538 uint32_t minimalDenseCount = requiredCapacity / SPARSE_DENSITY_RATIO;
539 if (newElementsHint >= minimalDenseCount) {
540 return false;
541 }
542 minimalDenseCount -= newElementsHint;
543
544 if (minimalDenseCount > cap) {
545 return true;
546 }
547
548 uint32_t initLen = getDenseInitializedLength();
549 if (denseElementsArePacked()) {
550 return minimalDenseCount > initLen;
551 }
552
553 const Value* elems = getDenseElements();
554 for (uint32_t i = 0; i < initLen; i++) {
555 if (!elems[i].isMagic(JS_ELEMENTS_HOLE) && !--minimalDenseCount) {
556 return false;
557 }
558 }
559 return true;
560 }
561
562 /* static */
563 DenseElementResult NativeObject::maybeDensifySparseElements(
564 JSContext* cx, Handle<NativeObject*> obj) {
565 /*
566 * Wait until after the object goes into dictionary mode, which must happen
567 * when sparsely packing any array with more than MIN_SPARSE_INDEX elements
568 * (see PropertyTree::MAX_HEIGHT).
569 */
570 if (!obj->inDictionaryMode()) {
571 return DenseElementResult::Incomplete;
572 }
573
574 /*
575 * Only measure the number of indexed properties every log(n) times when
576 * populating the object.
577 */
578 uint32_t slotSpan = obj->slotSpan();
579 if (slotSpan != RoundUpPow2(slotSpan)) {
580 return DenseElementResult::Incomplete;
581 }
582
583 /* Watch for conditions under which an object's elements cannot be dense. */
584 if (!obj->isExtensible()) {
585 return DenseElementResult::Incomplete;
586 }
587
588 /*
589 * The indexes in the object need to be sufficiently dense before they can
590 * be converted to dense mode.
591 */
592 uint32_t numDenseElements = 0;
593 uint32_t newInitializedLength = 0;
594
595 for (ShapePropertyIter<NoGC> iter(obj->shape()); !iter.done(); iter++) {
596 uint32_t index;
597 if (!IdIsIndex(iter->key(), &index)) {
598 continue;
599 }
600 if (iter->flags() != PropertyFlags::defaultDataPropFlags) {
601 // For simplicity, only densify the object if all indexed properties can
602 // be converted to dense elements.
603 return DenseElementResult::Incomplete;
604 }
605 MOZ_ASSERT(iter->isDataProperty());
606 numDenseElements++;
607 newInitializedLength = std::max(newInitializedLength, index + 1);
608 }
609
610 if (numDenseElements * SPARSE_DENSITY_RATIO < newInitializedLength) {
611 return DenseElementResult::Incomplete;
612 }
613
614 if (newInitializedLength > MAX_DENSE_ELEMENTS_COUNT) {
615 return DenseElementResult::Incomplete;
616 }
617
618 /*
619 * This object meets all necessary restrictions, convert all indexed
620 * properties into dense elements.
621 */
622
623 if (newInitializedLength > obj->getDenseCapacity()) {
624 if (!obj->growElements(cx, newInitializedLength)) {
625 return DenseElementResult::Failure;
626 }
627 }
628
629 obj->ensureDenseInitializedLength(newInitializedLength, 0);
630
631 if (obj->compartment()->objectMaybeInIteration(obj)) {
632 // Mark the densified elements as maybe-in-iteration. See also the comment
633 // in GetIterator.
634 obj->markDenseElementsMaybeInIteration();
635 }
636
637 if (!NativeObject::densifySparseElements(cx, obj)) {
638 return DenseElementResult::Failure;
639 }
640
641 return DenseElementResult::Success;
642 }
643
644 void NativeObject::moveShiftedElements() {
645 MOZ_ASSERT(isExtensible());
646
647 ObjectElements* header = getElementsHeader();
648 uint32_t numShifted = header->numShiftedElements();
649 MOZ_ASSERT(numShifted > 0);
650
651 uint32_t initLength = header->initializedLength;
652
653 ObjectElements* newHeader =
654 static_cast<ObjectElements*>(getUnshiftedElementsHeader());
655 memmove(newHeader, header, sizeof(ObjectElements));
656
657 newHeader->clearShiftedElements();
658 newHeader->capacity += numShifted;
659 elements_ = newHeader->elements();
660
661 // To move the elements, temporarily update initializedLength to include
662 // the shifted elements.
663 newHeader->initializedLength += numShifted;
664
665 // Move the elements. Initialize to |undefined| to ensure pre-barriers
666 // don't see garbage.
667 for (size_t i = 0; i < numShifted; i++) {
668 initDenseElement(i, UndefinedValue());
669 }
670 moveDenseElements(0, numShifted, initLength);
671
672 // Restore the initialized length. We use setDenseInitializedLength to
673 // make sure prepareElementRangeForOverwrite is called on the shifted
674 // elements.
675 setDenseInitializedLength(initLength);
676 }
677
678 void NativeObject::maybeMoveShiftedElements() {
679 MOZ_ASSERT(isExtensible());
680
681 ObjectElements* header = getElementsHeader();
682 MOZ_ASSERT(header->numShiftedElements() > 0);
683
684 // Move the elements if less than a third of the allocated space is in use.
685 if (header->capacity < header->numAllocatedElements() / 3) {
686 moveShiftedElements();
687 }
688 }
689
690 bool NativeObject::tryUnshiftDenseElements(uint32_t count) {
691 MOZ_ASSERT(isExtensible());
692 MOZ_ASSERT(count > 0);
693
694 ObjectElements* header = getElementsHeader();
695 uint32_t numShifted = header->numShiftedElements();
696
697 if (count > numShifted) {
698 // We need more elements than are easily available. Try to make space
699 // for more elements than we need (and shift the remaining ones) so
700 // that unshifting more elements later will be fast.
701
702 // Don't bother reserving elements if the number of elements is small.
703 // Note that there's no technical reason for using this particular
704 // limit.
705 if (header->initializedLength <= 10 ||
706 header->hasNonwritableArrayLength() ||
707 MOZ_UNLIKELY(count > ObjectElements::MaxShiftedElements)) {
708 return false;
709 }
710
711 MOZ_ASSERT(header->capacity >= header->initializedLength);
712 uint32_t unusedCapacity = header->capacity - header->initializedLength;
713
714 // Determine toShift, the number of extra elements we want to make
715 // available.
716 uint32_t toShift = count - numShifted;
717 MOZ_ASSERT(toShift <= ObjectElements::MaxShiftedElements,
718 "count <= MaxShiftedElements so toShift <= MaxShiftedElements");
719
720 // Give up if we need to allocate more elements.
721 if (toShift > unusedCapacity) {
722 return false;
723 }
724
725 // Move more elements than we need, so that other unshift calls will be
726 // fast. We just have to make sure we don't exceed unusedCapacity.
727 toShift = std::min(toShift + unusedCapacity / 2, unusedCapacity);
728
729 // Ensure |numShifted + toShift| does not exceed MaxShiftedElements.
730 if (numShifted + toShift > ObjectElements::MaxShiftedElements) {
731 toShift = ObjectElements::MaxShiftedElements - numShifted;
732 }
733
734 MOZ_ASSERT(count <= numShifted + toShift);
735 MOZ_ASSERT(numShifted + toShift <= ObjectElements::MaxShiftedElements);
736 MOZ_ASSERT(toShift <= unusedCapacity);
737
738 // Now move/unshift the elements.
739 uint32_t initLen = header->initializedLength;
740 setDenseInitializedLength(initLen + toShift);
741 for (uint32_t i = 0; i < toShift; i++) {
742 initDenseElement(initLen + i, UndefinedValue());
743 }
744 moveDenseElements(toShift, 0, initLen);
745
746 // Shift the elements we just prepended.
747 shiftDenseElementsUnchecked(toShift);
748
749 // We can now fall-through to the fast path below.
750 header = getElementsHeader();
751 MOZ_ASSERT(header->numShiftedElements() == numShifted + toShift);
752
753 numShifted = header->numShiftedElements();
754 MOZ_ASSERT(count <= numShifted);
755 }
756
757 elements_ -= count;
758 ObjectElements* newHeader = getElementsHeader();
759 memmove(newHeader, header, sizeof(ObjectElements));
760
761 newHeader->unshiftShiftedElements(count);
762
763 // Initialize to |undefined| to ensure pre-barriers don't see garbage.
764 for (uint32_t i = 0; i < count; i++) {
765 initDenseElement(i, UndefinedValue());
766 }
767
768 return true;
769 }
770
771 // Given a requested capacity (in elements) and (potentially) the length of an
772 // array for which elements are being allocated, compute an actual allocation
773 // amount (in elements). (Allocation amounts include space for an
774 // ObjectElements instance, so a return value of |N| implies
775 // |N - ObjectElements::VALUES_PER_HEADER| usable elements.)
776 //
777 // The requested/actual allocation distinction is meant to:
778 //
779 // * preserve amortized O(N) time to add N elements;
780 // * minimize the number of unused elements beyond an array's length, and
781 // * provide at least ELEMENT_CAPACITY_MIN elements no matter what (so adding
782 // the first several elements to small arrays only needs one allocation).
783 /* static */
784 bool NativeObject::goodElementsAllocationAmount(JSContext* cx,
785 uint32_t reqCapacity,
786 uint32_t length,
787 uint32_t* goodAmount) {
788 if (reqCapacity > MAX_DENSE_ELEMENTS_COUNT) {
789 ReportOutOfMemory(cx);
790 return false;
791 }
792
793 uint32_t reqAllocated = reqCapacity + ObjectElements::VALUES_PER_HEADER;
794
795 // Handle "small" requests primarily by doubling.
796 const uint32_t Mebi = 1 << 20;
797 if (reqAllocated < Mebi) {
798 uint32_t amount =
799 gc::GetGoodPower2ElementCount(reqAllocated, sizeof(Value));
800
801 // If |amount| would be 2/3 or more of the array's length, adjust
802 // it (up or down) to be equal to the array's length. This avoids
803 // allocating excess elements that aren't likely to be needed, either
804 // in this resizing or a subsequent one. The 2/3 factor is chosen so
805 // that exceptional resizings will at most triple the capacity, as
806 // opposed to the usual doubling.
807 uint32_t goodCapacity = amount - ObjectElements::VALUES_PER_HEADER;
808 if (length >= reqCapacity && goodCapacity > (length / 3) * 2) {
809 amount = gc::GetGoodElementCount(
810 length + ObjectElements::VALUES_PER_HEADER, sizeof(Value));
811 }
812
813 const size_t AmountMin =
814 ELEMENT_CAPACITY_MIN + ObjectElements::VALUES_PER_HEADER;
815
816 // Check this size doesn't waste any space in the allocation.
817 MOZ_ASSERT(AmountMin == gc::GetGoodElementCount(AmountMin, sizeof(Value)));
818
819 if (amount < AmountMin) {
820 amount = AmountMin;
821 }
822
823 *goodAmount = amount;
824
825 return true;
826 }
827
828 // The almost-doubling above wastes a lot of space for larger bucket sizes.
829 // For large amounts, switch to bucket sizes that obey this formula:
830 //
831 // count(n+1) = Math.ceil(count(n) * 1.125)
832 //
833 // where |count(n)| is the size of the nth bucket, measured in 2**20 slots.
834 // These bucket sizes still preserve amortized O(N) time to add N elements,
835 // just with a larger constant factor.
836 //
837 // The bucket size table below was generated with this JavaScript (and
838 // manual reformatting):
839 //
840 // for (let n = 1, i = 0; i < 34; i++) {
841 // print('0x' + (n * (1 << 20)).toString(16) + ', ');
842 // n = Math.ceil(n * 1.125);
843 // }
844 static constexpr uint32_t BigBuckets[] = {
845 0x100000, 0x200000, 0x300000, 0x400000, 0x500000, 0x600000,
846 0x700000, 0x800000, 0x900000, 0xb00000, 0xd00000, 0xf00000,
847 0x1100000, 0x1400000, 0x1700000, 0x1a00000, 0x1e00000, 0x2200000,
848 0x2700000, 0x2c00000, 0x3200000, 0x3900000, 0x4100000, 0x4a00000,
849 0x5400000, 0x5f00000, 0x6b00000, 0x7900000, 0x8900000, 0x9b00000,
850 0xaf00000, 0xc500000, 0xde00000, 0xfa00000};
851 static_assert(BigBuckets[std::size(BigBuckets) - 1] <=
852 MAX_DENSE_ELEMENTS_ALLOCATION);
853
854 // We will allocate these in large buffers so account for the header size
855 // required there.
856 static_assert(sizeof(Value) * Mebi >= gc::ChunkSize);
857
858 // Pick the first bucket that'll fit |reqAllocated|.
859 for (uint32_t b : BigBuckets) {
860 if (b >= reqAllocated) {
861 MOZ_ASSERT(b == gc::GetGoodElementCount(b, sizeof(Value)));
862 *goodAmount = b;
863 return true;
864 }
865 }
866
867 // Otherwise, return the maximum bucket size.
868 *goodAmount = MAX_DENSE_ELEMENTS_ALLOCATION;
869 return true;
870 }
871
872 bool NativeObject::growElements(JSContext* cx, uint32_t reqCapacity) {
873 MOZ_ASSERT(isExtensible());
874 MOZ_ASSERT(canHaveNonEmptyElements());
875
876 // If there are shifted elements, consider moving them first. If we don't
877 // move them here, the code below will include the shifted elements in the
878 // resize.
879 uint32_t numShifted = getElementsHeader()->numShiftedElements();
880 if (numShifted > 0) {
881 // If the number of elements is small, it's cheaper to just move them as
882 // it may avoid a malloc/realloc. Note that there's no technical reason
883 // for using this particular value, but it works well in real-world use
884 // cases.
885 static const size_t MaxElementsToMoveEagerly = 20;
886
887 if (getElementsHeader()->initializedLength <= MaxElementsToMoveEagerly) {
888 moveShiftedElements();
889 } else {
890 maybeMoveShiftedElements();
891 }
892 if (getDenseCapacity() >= reqCapacity) {
893 return true;
894 }
895 // moveShiftedElements() may have changed the number of shifted elements;
896 // update `numShifted` accordingly.
897 numShifted = getElementsHeader()->numShiftedElements();
898
899 // If |reqCapacity + numShifted| overflows, we just move all shifted
900 // elements to avoid the problem.
901 CheckedInt<uint32_t> checkedReqCapacity(reqCapacity);
902 checkedReqCapacity += numShifted;
903 if (MOZ_UNLIKELY(!checkedReqCapacity.isValid())) {
904 moveShiftedElements();
905 numShifted = 0;
906 }
907 }
908
909 uint32_t oldCapacity = getDenseCapacity();
910 MOZ_ASSERT(oldCapacity < reqCapacity);
911
912 uint32_t newAllocated = 0;
913 if (is<ArrayObject>() && !as<ArrayObject>().lengthIsWritable()) {
914 // Preserve the |capacity <= length| invariant for arrays with
915 // non-writable length. See also js::ArraySetLength which initially
916 // enforces this requirement.
917 MOZ_ASSERT(reqCapacity <= as<ArrayObject>().length());
918 // Adding to reqCapacity must not overflow uint32_t.
919 MOZ_ASSERT(reqCapacity <= MAX_DENSE_ELEMENTS_COUNT);
920
921 // Then, add the header and shifted elements sizes to the new capacity
922 // to get the overall amount to allocate.
923 newAllocated = reqCapacity + numShifted + ObjectElements::VALUES_PER_HEADER;
924 } else {
925 // For arrays with writable length, and all non-Array objects, call
926 // `NativeObject::goodElementsAllocationAmount()` to determine the
927 // amount to allocate from the the requested capacity and existing length.
928 uint32_t length = is<ArrayObject>() ? as<ArrayObject>().length() : 0;
929 if (!goodElementsAllocationAmount(cx, reqCapacity + numShifted, length,
930 &newAllocated)) {
931 return false;
932 }
933 }
934
935 // newAllocated now contains the size of the buffer we need to allocate;
936 // subtract off the header and shifted elements size to get the new capacity
937 uint32_t newCapacity =
938 newAllocated - ObjectElements::VALUES_PER_HEADER - numShifted;
939 // If the new capacity isn't strictly greater than the old capacity, then this
940 // method shouldn't have been called; if the new capacity doesn't satisfy
941 // what was requested, then one of the calculations above must have been
942 // wrong.
943 MOZ_ASSERT(newCapacity > oldCapacity && newCapacity >= reqCapacity);
944
945 // If newCapacity exceeds MAX_DENSE_ELEMENTS_COUNT, the array should become
946 // sparse.
947 MOZ_ASSERT(newCapacity <= MAX_DENSE_ELEMENTS_COUNT);
948
949 uint32_t initlen = getDenseInitializedLength();
950
951 HeapSlot* oldHeaderSlots =
952 reinterpret_cast<HeapSlot*>(getUnshiftedElementsHeader());
953 HeapSlot* newHeaderSlots;
954 uint32_t oldAllocated = 0;
955 if (hasDynamicElements()) {
956 // If the object has dynamic elements, then we might be able to resize the
957 // buffer in-place.
958
959 // First, check that adding to oldCapacity won't overflow uint32_t
960 MOZ_ASSERT(oldCapacity <= MAX_DENSE_ELEMENTS_COUNT);
961 // Then, add the header and shifted elements sizes to get the overall size
962 // of the existing buffer
963 oldAllocated = oldCapacity + ObjectElements::VALUES_PER_HEADER + numShifted;
964
965 // Finally, try to resize the buffer.
966 newHeaderSlots = ReallocateCellBuffer<HeapSlot>(cx, this, oldHeaderSlots,
967 oldAllocated, newAllocated);
968 if (!newHeaderSlots) {
969 return false; // If the resizing failed, then we leave elements at its
970 // old size.
971 }
972 } else {
973 // If the object has fixed elements, then we always need to allocate a new
974 // buffer, because if we've reached this code, then the requested capacity
975 // is greater than the existing inline space available within the object
976 newHeaderSlots = AllocateCellBuffer<HeapSlot>(cx, this, newAllocated);
977 if (!newHeaderSlots) {
978 return false; // Leave elements at its old size.
979 }
980
981 // Copy the initialized elements into the new buffer,
982 PodCopy(newHeaderSlots, oldHeaderSlots,
983 ObjectElements::VALUES_PER_HEADER + initlen + numShifted);
984 }
985
986 ObjectElements* newheader = reinterpret_cast<ObjectElements*>(newHeaderSlots);
987 // Update the elements pointer to point to the new elements buffer.
988 elements_ = newheader->elements() + numShifted;
989
990 // Clear the "fixed elements" flag, because if this code has been reached,
991 // this object now has dynamic elements.
992 getElementsHeader()->flags &= ~ObjectElements::FIXED;
993 getElementsHeader()->capacity = newCapacity;
994
995 // Poison the uninitialized portion of the new elements buffer.
996 Debug_SetSlotRangeToCrashOnTouch(elements_ + initlen, newCapacity - initlen);
997
998 return true;
999 }
1000
1001 void NativeObject::shrinkElements(JSContext* cx, uint32_t reqCapacity) {
1002 MOZ_ASSERT(canHaveNonEmptyElements());
1003 MOZ_ASSERT(reqCapacity >= getDenseInitializedLength());
1004
1005 if (!hasDynamicElements()) {
1006 return;
1007 }
1008
1009 // If we have shifted elements, consider moving them.
1010 uint32_t numShifted = getElementsHeader()->numShiftedElements();
1011 if (numShifted > 0) {
1012 maybeMoveShiftedElements();
1013 numShifted = getElementsHeader()->numShiftedElements();
1014 }
1015
1016 uint32_t oldCapacity = getDenseCapacity();
1017 MOZ_ASSERT(reqCapacity < oldCapacity);
1018
1019 uint32_t newAllocated = 0;
1020 MOZ_ALWAYS_TRUE(goodElementsAllocationAmount(cx, reqCapacity + numShifted, 0,
1021 &newAllocated));
1022 MOZ_ASSERT(oldCapacity <= MAX_DENSE_ELEMENTS_COUNT);
1023
1024 uint32_t oldAllocated =
1025 oldCapacity + ObjectElements::VALUES_PER_HEADER + numShifted;
1026 if (newAllocated == oldAllocated) {
1027 return; // Leave elements at its old size.
1028 }
1029
1030 MOZ_ASSERT(newAllocated > ObjectElements::VALUES_PER_HEADER);
1031 uint32_t newCapacity =
1032 newAllocated - ObjectElements::VALUES_PER_HEADER - numShifted;
1033 MOZ_ASSERT(newCapacity <= MAX_DENSE_ELEMENTS_COUNT);
1034
1035 HeapSlot* oldHeaderSlots =
1036 reinterpret_cast<HeapSlot*>(getUnshiftedElementsHeader());
1037 HeapSlot* newHeaderSlots = ReallocateCellBuffer<HeapSlot>(
1038 cx, this, oldHeaderSlots, oldAllocated, newAllocated);
1039 if (!newHeaderSlots) {
1040 cx->recoverFromOutOfMemory();
1041 return; // Leave elements at its old size.
1042 }
1043
1044 ObjectElements* newheader = reinterpret_cast<ObjectElements*>(newHeaderSlots);
1045 elements_ = newheader->elements() + numShifted;
1046 getElementsHeader()->capacity = newCapacity;
1047 }
1048
1049 void NativeObject::shrinkCapacityToInitializedLength(JSContext* cx) {
1050 // When an array's length becomes non-writable, writes to indexes greater
1051 // greater than or equal to the length don't change the array. We handle this
1052 // with a check for non-writable length in most places. But in JIT code every
1053 // check counts -- so we piggyback the check on the already-required range
1054 // check for |index < capacity| by making capacity of arrays with non-writable
1055 // length never exceed the length. This mechanism is also used when an object
1056 // becomes non-extensible.
1057
1058 if (getElementsHeader()->numShiftedElements() > 0) {
1059 moveShiftedElements();
1060 }
1061
1062 ObjectElements* header = getElementsHeader();
1063 uint32_t len = header->initializedLength;
1064 MOZ_ASSERT(header->capacity >= len);
1065 if (header->capacity == len) {
1066 return;
1067 }
1068
1069 shrinkElements(cx, len);
1070
1071 getElementsHeader()->capacity = len;
1072 }
1073
1074 /* static */
1075 bool NativeObject::allocDictionarySlot(JSContext* cx, Handle<NativeObject*> obj,
1076 uint32_t* slotp) {
1077 MOZ_ASSERT(obj->inDictionaryMode());
1078
1079 uint32_t slotSpan = obj->slotSpan();
1080 MOZ_ASSERT(slotSpan >= JSSLOT_FREE(obj->getClass()));
1081
1082 // Try to pull a free slot from the slot-number free list.
1083 DictionaryPropMap* map = obj->dictionaryShape()->propMap();
1084 uint32_t last = map->freeList();
1085 if (last != SHAPE_INVALID_SLOT) {
1086 #ifdef DEBUG
1087 MOZ_ASSERT(last < slotSpan);
1088 uint32_t next = obj->getSlot(last).toPrivateUint32();
1089 MOZ_ASSERT_IF(next != SHAPE_INVALID_SLOT, next < slotSpan);
1090 #endif
1091 *slotp = last;
1092 const Value& vref = obj->getSlot(last);
1093 map->setFreeList(vref.toPrivateUint32());
1094 obj->setSlot(last, UndefinedValue());
1095 return true;
1096 }
1097
1098 if (MOZ_UNLIKELY(slotSpan >= SHAPE_MAXIMUM_SLOT)) {
1099 ReportOutOfMemory(cx);
1100 return false;
1101 }
1102
1103 *slotp = slotSpan;
1104
1105 uint32_t numFixed = obj->numFixedSlots();
1106 if (slotSpan < numFixed) {
1107 obj->initFixedSlot(slotSpan, UndefinedValue());
1108 obj->setDictionaryModeSlotSpan(slotSpan + 1);
1109 return true;
1110 }
1111
1112 uint32_t dynamicSlotIndex = slotSpan - numFixed;
1113 if (dynamicSlotIndex >= obj->numDynamicSlots()) {
1114 if (MOZ_UNLIKELY(!obj->growSlotsForNewSlot(cx, numFixed, slotSpan))) {
1115 return false;
1116 }
1117 }
1118 obj->initDynamicSlot(numFixed, slotSpan, UndefinedValue());
1119 obj->setDictionaryModeSlotSpan(slotSpan + 1);
1120 return true;
1121 }
1122
1123 void NativeObject::freeDictionarySlot(uint32_t slot) {
1124 MOZ_ASSERT(inDictionaryMode());
1125 MOZ_ASSERT(slot < slotSpan());
1126
1127 DictionaryPropMap* map = dictionaryShape()->propMap();
1128 uint32_t last = map->freeList();
1129
1130 // Can't afford to check the whole free list, but let's check the head.
1131 MOZ_ASSERT_IF(last != SHAPE_INVALID_SLOT, last < slotSpan() && last != slot);
1132
1133 // Place all freed slots other than reserved slots (bug 595230) on the
1134 // dictionary's free list.
1135 if (JSSLOT_FREE(getClass()) <= slot) {
1136 MOZ_ASSERT_IF(last != SHAPE_INVALID_SLOT, last < slotSpan());
1137 setSlot(slot, PrivateUint32Value(last));
1138 map->setFreeList(slot);
1139 } else {
1140 setSlot(slot, UndefinedValue());
1141 }
1142 }
1143
1144 template <AllowGC allowGC>
1145 bool js::NativeLookupOwnProperty(
1146 JSContext* cx, typename MaybeRooted<NativeObject*, allowGC>::HandleType obj,
1147 typename MaybeRooted<jsid, allowGC>::HandleType id, PropertyResult* propp) {
1148 return NativeLookupOwnPropertyInline<allowGC>(cx, obj, id, propp);
1149 }
1150
1151 template bool js::NativeLookupOwnProperty<CanGC>(JSContext* cx,
1152 Handle<NativeObject*> obj,
1153 HandleId id,
1154 PropertyResult* propp);
1155
1156 template bool js::NativeLookupOwnProperty<NoGC>(JSContext* cx,
1157 NativeObject* const& obj,
1158 const jsid& id,
1159 PropertyResult* propp);
1160
1161 /*** [[DefineOwnProperty]] **************************************************/
1162
1163 static bool CallJSAddPropertyOp(JSContext* cx, JSAddPropertyOp op,
1164 HandleObject obj, HandleId id, HandleValue v) {
1165 cx->check(obj, id, v);
1166 return op(cx, obj, id, v);
1167 }
1168
1169 static MOZ_ALWAYS_INLINE bool CallAddPropertyHook(JSContext* cx,
1170 Handle<NativeObject*> obj,
1171 HandleId id,
1172 HandleValue value) {
1173 JSAddPropertyOp addProperty = obj->getClass()->getAddProperty();
1174 if (MOZ_UNLIKELY(addProperty)) {
1175 if (!CallJSAddPropertyOp(cx, addProperty, obj, id, value)) {
1176 NativeObject::removeProperty(cx, obj, id);
1177 return false;
1178 }
1179 }
1180 return true;
1181 }
1182
1183 static MOZ_ALWAYS_INLINE bool CallAddPropertyHookDense(
1184 JSContext* cx, Handle<NativeObject*> obj, uint32_t index,
1185 HandleValue value) {
1186 // Inline addProperty for array objects.
1187 if (obj->is<ArrayObject>()) {
1188 ArrayObject* arr = &obj->as<ArrayObject>();
1189 uint32_t length = arr->length();
1190 if (index >= length) {
1191 arr->setLength(cx, index + 1);
1192 }
1193 return true;
1194 }
1195
1196 JSAddPropertyOp addProperty = obj->getClass()->getAddProperty();
1197 if (MOZ_UNLIKELY(addProperty)) {
1198 RootedId id(cx, PropertyKey::Int(index));
1199 if (!CallJSAddPropertyOp(cx, addProperty, obj, id, value)) {
1200 obj->setDenseElementHole(index);
1201 return false;
1202 }
1203 }
1204 return true;
1205 }
1206
1207 /**
1208 * Determines whether a write to the given element on |arr| should fail
1209 * because |arr| has a non-writable length, and writing that element would
1210 * increase the length of the array.
1211 */
1212 static bool WouldDefinePastNonwritableLength(ArrayObject* arr, uint32_t index) {
1213 return !arr->lengthIsWritable() && index >= arr->length();
1214 }
1215
1216 static bool ChangeProperty(JSContext* cx, Handle<NativeObject*> obj,
1217 HandleId id, HandleObject getter,
1218 HandleObject setter, PropertyFlags flags,
1219 PropertyResult* existing, uint32_t* slotOut) {
1220 MOZ_ASSERT(existing);
1221
1222 Rooted<GetterSetter*> gs(cx);
1223
1224 // If we're redefining a getter/setter property but the getter and setter
1225 // objects are still the same, use the existing GetterSetter.
1226 if (existing->isNativeProperty()) {
1227 PropertyInfo prop = existing->propertyInfo();
1228 if (prop.isAccessorProperty()) {
1229 GetterSetter* current = obj->getGetterSetter(prop);
1230 if (current->getter() == getter && current->setter() == setter) {
1231 gs = current;
1232 }
1233 }
1234 }
1235
1236 if (!gs) {
1237 gs = GetterSetter::create(cx, getter, setter);
1238 if (!gs) {
1239 return false;
1240 }
1241 }
1242
1243 if (existing->isNativeProperty()) {
1244 Rooted<Value> value(cx, PrivateGCThingValue(gs));
1245 if (!NativeObject::changeProperty(cx, obj, id, flags, slotOut)) {
1246 return false;
1247 }
1248 Watchtower::watchPropertyValueChange<AllowGC::CanGC>(
1249 cx, obj, id, value, existing->propertyInfo());
1250 obj->setSlot(*slotOut, value);
1251 return true;
1252 }
1253
1254 if (!NativeObject::addProperty(cx, obj, id, flags, slotOut)) {
1255 return false;
1256 }
1257 obj->initSlot(*slotOut, PrivateGCThingValue(gs));
1258 return true;
1259 }
1260
1261 static PropertyFlags ComputePropertyFlags(const PropertyDescriptor& desc) {
1262 desc.assertComplete();
1263
1264 PropertyFlags flags;
1265 flags.setFlag(PropertyFlag::Configurable, desc.configurable());
1266 flags.setFlag(PropertyFlag::Enumerable, desc.enumerable());
1267
1268 if (desc.isDataDescriptor()) {
1269 flags.setFlag(PropertyFlag::Writable, desc.writable());
1270 } else {
1271 MOZ_ASSERT(desc.isAccessorDescriptor());
1272 flags.setFlag(PropertyFlag::AccessorProperty);
1273 }
1274
1275 return flags;
1276 }
1277
1278 // Whether we're adding a new property or changing an existing property (this
1279 // can be either a property stored in the shape tree or a dense element).
1280 enum class IsAddOrChange { Add, Change };
1281
1282 template <IsAddOrChange AddOrChange>
1283 static MOZ_ALWAYS_INLINE bool AddOrChangeProperty(
1284 JSContext* cx, Handle<NativeObject*> obj, HandleId id,
1285 Handle<PropertyDescriptor> desc, PropertyResult* existing = nullptr) {
1286 desc.assertComplete();
1287
1288 #ifdef DEBUG
1289 if constexpr (AddOrChange == IsAddOrChange::Add) {
1290 MOZ_ASSERT(existing == nullptr);
1291 MOZ_ASSERT(!obj->containsPure(id));
1292 } else {
1293 static_assert(AddOrChange == IsAddOrChange::Change);
1294 MOZ_ASSERT(existing);
1295 MOZ_ASSERT(existing->isNativeProperty() || existing->isDenseElement());
1296 }
1297 #endif
1298
1299 // Use dense storage for indexed properties where possible: when we have an
1300 // integer key with default property attributes and are either adding a new
1301 // property or changing a dense element.
1302 PropertyFlags flags = ComputePropertyFlags(desc);
1303 if (id.isInt() && flags == PropertyFlags::defaultDataPropFlags &&
1304 (AddOrChange == IsAddOrChange::Add || existing->isDenseElement())) {
1305 MOZ_ASSERT(!desc.isAccessorDescriptor());
1306 MOZ_ASSERT(!obj->is<TypedArrayObject>());
1307 uint32_t index = id.toInt();
1308 DenseElementResult edResult = obj->ensureDenseElements(cx, index, 1);
1309 if (edResult == DenseElementResult::Failure) {
1310 return false;
1311 }
1312 if (edResult == DenseElementResult::Success) {
1313 obj->setDenseElement(index, desc.value());
1314 if (!CallAddPropertyHookDense(cx, obj, index, desc.value())) {
1315 return false;
1316 }
1317 return true;
1318 }
1319 }
1320
1321 uint32_t slot;
1322 if constexpr (AddOrChange == IsAddOrChange::Add) {
1323 if (desc.isAccessorDescriptor()) {
1324 Rooted<GetterSetter*> gs(
1325 cx, GetterSetter::create(cx, desc.getter(), desc.setter()));
1326 if (!gs) {
1327 return false;
1328 }
1329 if (!NativeObject::addProperty(cx, obj, id, flags, &slot)) {
1330 return false;
1331 }
1332 obj->initSlot(slot, PrivateGCThingValue(gs));
1333 } else {
1334 if (!NativeObject::addProperty(cx, obj, id, flags, &slot)) {
1335 return false;
1336 }
1337 obj->initSlot(slot, desc.value());
1338 }
1339 } else {
1340 if (desc.isAccessorDescriptor()) {
1341 if (!ChangeProperty(cx, obj, id, desc.getter(), desc.setter(), flags,
1342 existing, &slot)) {
1343 return false;
1344 }
1345 } else {
1346 if (existing->isNativeProperty()) {
1347 if (!NativeObject::changeProperty(cx, obj, id, flags, &slot)) {
1348 return false;
1349 }
1350 Watchtower::watchPropertyValueChange<AllowGC::CanGC>(
1351 cx, obj, id, desc.value(), existing->propertyInfo());
1352 obj->setSlot(slot, desc.value());
1353 } else {
1354 if (!NativeObject::addProperty(cx, obj, id, flags, &slot)) {
1355 return false;
1356 }
1357 obj->initSlot(slot, desc.value());
1358 }
1359 }
1360 }
1361
1362 MOZ_ASSERT(slot < obj->slotSpan());
1363
1364 // Clear any existing dense index after adding a sparse indexed property,
1365 // and investigate converting the object to dense indexes.
1366 if (id.isInt()) {
1367 uint32_t index = id.toInt();
1368 if constexpr (AddOrChange == IsAddOrChange::Add) {
1369 MOZ_ASSERT(!obj->containsDenseElement(index));
1370 } else {
1371 obj->removeDenseElementForSparseIndex(index);
1372 }
1373 // Only try to densify sparse elements if the property we just added/changed
1374 // is in the last slot. This avoids a perf cliff in pathological cases: in
1375 // maybeDensifySparseElements we densify if the slot span is a power-of-two,
1376 // but if we get slots from the free list, the slot span will stay the same
1377 // until the free list is empty. This means we'd get quadratic behavior by
1378 // trying to densify for each sparse element we add. See bug 1782487.
1379 if (slot == obj->slotSpan() - 1) {
1380 DenseElementResult edResult =
1381 NativeObject::maybeDensifySparseElements(cx, obj);
1382 if (edResult == DenseElementResult::Failure) {
1383 return false;
1384 }
1385 if (edResult == DenseElementResult::Success) {
1386 MOZ_ASSERT(!desc.isAccessorDescriptor());
1387 return CallAddPropertyHookDense(cx, obj, index, desc.value());
1388 }
1389 }
1390 }
1391
1392 if (desc.isDataDescriptor()) {
1393 return CallAddPropertyHook(cx, obj, id, desc.value());
1394 }
1395
1396 return CallAddPropertyHook(cx, obj, id, UndefinedHandleValue);
1397 }
1398
1399 // Versions of AddOrChangeProperty optimized for adding a plain data property.
1400 // This function doesn't handle integer ids as we may have to store them in
1401 // dense elements.
1402 static MOZ_ALWAYS_INLINE bool AddDataProperty(JSContext* cx,
1403 Handle<NativeObject*> obj,
1404 HandleId id, HandleValue v) {
1405 MOZ_ASSERT(!id.isInt());
1406
1407 uint32_t slot;
1408 if (!NativeObject::addProperty(cx, obj, id,
1409 PropertyFlags::defaultDataPropFlags, &slot)) {
1410 return false;
1411 }
1412
1413 obj->initSlot(slot, v);
1414
1415 return CallAddPropertyHook(cx, obj, id, v);
1416 }
1417
1418 bool js::AddSlotAndCallAddPropHook(JSContext* cx, Handle<NativeObject*> obj,
1419 HandleValue v, Handle<Shape*> newShape) {
1420 MOZ_ASSERT(obj->getClass()->getAddProperty());
1421 MOZ_ASSERT(newShape->asShared().lastProperty().isDataProperty());
1422
1423 RootedId id(cx, newShape->asShared().lastProperty().key());
1424 MOZ_ASSERT(!id.isInt());
1425
1426 uint32_t slot = newShape->asShared().lastProperty().slot();
1427 if (!obj->setShapeAndAddNewSlot(cx, &newShape->asShared(), slot)) {
1428 return false;
1429 }
1430 obj->initSlot(slot, v);
1431
1432 return CallAddPropertyHook(cx, obj, id, v);
1433 }
1434
1435 static bool IsAccessorDescriptor(const PropertyResult& prop) {
1436 if (prop.isNativeProperty()) {
1437 return prop.propertyInfo().isAccessorProperty();
1438 }
1439
1440 MOZ_ASSERT(prop.isDenseElement() || prop.isTypedArrayElement());
1441 return false;
1442 }
1443
1444 static bool IsDataDescriptor(const PropertyResult& prop) {
1445 return !IsAccessorDescriptor(prop);
1446 }
1447
1448 static bool GetCustomDataProperty(JSContext* cx, HandleObject obj, HandleId id,
1449 MutableHandleValue vp);
1450
1451 static bool GetExistingDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1452 HandleId id, const PropertyResult& prop,
1453 MutableHandleValue vp) {
1454 if (prop.isDenseElement()) {
1455 vp.set(obj->getDenseElement(prop.denseElementIndex()));
1456 return true;
1457 }
1458 if (prop.isTypedArrayElement()) {
1459 size_t idx = prop.typedArrayElementIndex();
1460 return obj->as<TypedArrayObject>().getElement<CanGC>(cx, idx, vp);
1461 }
1462
1463 PropertyInfo propInfo = prop.propertyInfo();
1464 if (propInfo.isDataProperty()) {
1465 vp.set(obj->getSlot(propInfo.slot()));
1466 return true;
1467 }
1468
1469 MOZ_RELEASE_ASSERT(propInfo.isCustomDataProperty());
1470 return GetCustomDataProperty(cx, obj, id, vp);
1471 }
1472
1473 /*
1474 * If desc is redundant with an existing own property obj[id], then set
1475 * |*redundant = true| and return true.
1476 */
1477 static bool DefinePropertyIsRedundant(JSContext* cx, Handle<NativeObject*> obj,
1478 HandleId id, const PropertyResult& prop,
1479 JS::PropertyAttributes attrs,
1480 Handle<PropertyDescriptor> desc,
1481 bool* redundant) {
1482 *redundant = false;
1483
1484 if (desc.hasConfigurable() && desc.configurable() != attrs.configurable()) {
1485 return true;
1486 }
1487 if (desc.hasEnumerable() && desc.enumerable() != attrs.enumerable()) {
1488 return true;
1489 }
1490 if (desc.isDataDescriptor()) {
1491 if (IsAccessorDescriptor(prop)) {
1492 return true;
1493 }
1494 if (desc.hasWritable() && desc.writable() != attrs.writable()) {
1495 return true;
1496 }
1497 if (desc.hasValue()) {
1498 // Get the current value of the existing property.
1499 RootedValue currentValue(cx);
1500 if (!GetExistingDataProperty(cx, obj, id, prop, &currentValue)) {
1501 return false;
1502 }
1503
1504 // Don't call SameValue here to ensure we properly update distinct
1505 // NaN values.
1506 if (desc.value() != currentValue) {
1507 return true;
1508 }
1509 }
1510
1511 // Check for custom data properties for ArrayObject/ArgumentsObject.
1512 // PropertyDescriptor can't represent these properties so they're never
1513 // redundant.
1514 if (prop.isNativeProperty() && prop.propertyInfo().isCustomDataProperty()) {
1515 return true;
1516 }
1517 } else if (desc.isAccessorDescriptor()) {
1518 if (!prop.isNativeProperty()) {
1519 return true;
1520 }
1521 PropertyInfo propInfo = prop.propertyInfo();
1522 if (desc.hasGetter() && (!propInfo.isAccessorProperty() ||
1523 desc.getter() != obj->getGetter(propInfo))) {
1524 return true;
1525 }
1526 if (desc.hasSetter() && (!propInfo.isAccessorProperty() ||
1527 desc.setter() != obj->getSetter(propInfo))) {
1528 return true;
1529 }
1530 }
1531
1532 *redundant = true;
1533 return true;
1534 }
1535
1536 bool js::NativeDefineProperty(JSContext* cx, Handle<NativeObject*> obj,
1537 HandleId id, Handle<PropertyDescriptor> desc_,
1538 ObjectOpResult& result) {
1539 desc_.assertValid();
1540
1541 // Section numbers and step numbers below refer to ES2025, draft rev
1542 // ac21460fedf4b926520b06c9820bdbebad596a8b.
1543 //
1544 // This function aims to implement 10.1.6 [[DefineOwnProperty]] as well as
1545 // the [[DefineOwnProperty]] methods described in 10.4.2.1 (arrays), 10.4.4.2
1546 // (arguments), and 10.4.5.3 (typed arrays).
1547
1548 // Dispense with custom behavior of exotic native objects first.
1549 if (obj->is<ArrayObject>()) {
1550 // 10.4.2.1 step 1. Redefining an array's length is very special.
1551 auto arr = HandleObject(obj).as<ArrayObject>();
1552 if (id == NameToId(cx->names().length)) {
1553 // 10.1.6.3 ValidateAndApplyPropertyDescriptor, step 5.c.
1554 if (desc_.isAccessorDescriptor()) {
1555 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1556 }
1557
1558 return ArraySetLength(cx, arr, id, desc_, result);
1559 }
1560
1561 // 10.4.2.1 step 2. Don't extend a fixed-length array.
1562 uint32_t index;
1563 if (IdIsIndex(id, &index)) {
1564 if (WouldDefinePastNonwritableLength(arr, index)) {
1565 return result.fail(JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH);
1566 }
1567 }
1568 } else if (obj->is<TypedArrayObject>()) {
1569 // 10.4.5.3 step 1. Indexed properties of typed arrays are special.
1570 if (mozilla::Maybe<uint64_t> index = ToTypedArrayIndex(id)) {
1571 auto tobj = HandleObject(obj).as<TypedArrayObject>();
1572 return DefineTypedArrayElement(cx, tobj, index.value(), desc_, result);
1573 }
1574 } else if (obj->is<ArgumentsObject>() && !desc_.resolving()) {
1575 auto argsobj = HandleObject(obj).as<ArgumentsObject>();
1576 if (id.isAtom(cx->names().length)) {
1577 // Either we are resolving the .length property on this object,
1578 // or redefining it. In the latter case only, we must reify the
1579 // property.
1580 if (!ArgumentsObject::reifyLength(cx, argsobj)) {
1581 return false;
1582 }
1583 } else if (id.isAtom(cx->names().callee) &&
1584 obj->is<MappedArgumentsObject>()) {
1585 // Do same thing as .length for .callee on MappedArgumentsObject.
1586 auto mapped = HandleObject(argsobj).as<MappedArgumentsObject>();
1587 if (!MappedArgumentsObject::reifyCallee(cx, mapped)) {
1588 return false;
1589 }
1590 } else if (id.isWellKnownSymbol(JS::SymbolCode::iterator)) {
1591 // Do same thing as .length for [@@iterator].
1592 if (!ArgumentsObject::reifyIterator(cx, argsobj)) {
1593 return false;
1594 }
1595 } else if (id.isInt()) {
1596 argsobj->markElementOverridden();
1597 }
1598 }
1599
1600 // 10.1.6.1 OrdinaryDefineOwnProperty step 1.
1601 PropertyResult prop;
1602 if (desc_.resolving()) {
1603 // We are being called from a resolve or enumerate hook to reify a
1604 // lazily-resolved property. To avoid reentering the resolve hook and
1605 // recursing forever, skip the resolve hook when doing this lookup.
1606 if (!NativeLookupOwnPropertyNoResolve(cx, obj, id, &prop)) {
1607 return false;
1608 }
1609 } else {
1610 if (!NativeLookupOwnProperty<CanGC>(cx, obj, id, &prop)) {
1611 return false;
1612 }
1613 }
1614 MOZ_ASSERT(!prop.isTypedArrayElement());
1615
1616 // From this point, the step numbers refer to
1617 // 10.1.6.3, ValidateAndApplyPropertyDescriptor.
1618 // Step 1 is a redundant assertion.
1619
1620 // Filling in desc: Here we make a copy of the desc_ argument. We will turn
1621 // it into a complete descriptor before updating obj. The spec algorithm
1622 // does not explicitly do this, but the end result is the same. Search for
1623 // "fill in" below for places where the filling-in actually occurs.
1624 Rooted<PropertyDescriptor> desc(cx, desc_);
1625
1626 // Step 2.
1627 if (prop.isNotFound()) {
1628 // Note: We are sharing the property definition machinery with private
1629 // fields. Private fields may be added to non-extensible objects.
1630 if (!obj->isExtensible() && !id.isPrivateName()) {
1631 return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
1632 }
1633
1634 // Fill in missing desc fields with defaults.
1635 CompletePropertyDescriptor(&desc);
1636
1637 if (!AddOrChangeProperty<IsAddOrChange::Add>(cx, obj, id, desc)) {
1638 return false;
1639 }
1640 return result.succeed();
1641 }
1642
1643 // Step 3 is an assertion.
1644
1645 // Step 4 and 5 (partially). Prop might not actually have a real shape, e.g.
1646 // in the case of dense array elements, GetPropertyAttributes is used to
1647 // paper-over that difference.
1648 JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
1649 bool redundant;
1650 if (!DefinePropertyIsRedundant(cx, obj, id, prop, attrs, desc, &redundant)) {
1651 return false;
1652 }
1653 if (redundant) {
1654 return result.succeed();
1655 }
1656
1657 // Step 5.
1658 if (!attrs.configurable()) {
1659 // Step 5.a.
1660 if (desc.hasConfigurable() && desc.configurable()) {
1661 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1662 }
1663
1664 // Step 5.b.
1665 if (desc.hasEnumerable() && desc.enumerable() != attrs.enumerable()) {
1666 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1667 }
1668
1669 MOZ_ASSERT(
1670 !desc.isGenericDescriptor(),
1671 "redundant or conflicting generic property descriptor already handled");
1672
1673 // Steps 5.c-d.
1674 //
1675 // If this is an existing accessor property and the property definition is
1676 // non-redundant, this must be an attempt to change an accessor function or
1677 // a redefinition to a data property. Both operations are invalid.
1678 //
1679 // If this is an existing data property and the incoming property descriptor
1680 // is an accessor property descriptor, this is an invalid redefinition to an
1681 // accessor property.
1682 if (IsAccessorDescriptor(prop) || desc.isAccessorDescriptor()) {
1683 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1684 }
1685
1686 // Step 5.e.
1687 if (!attrs.writable()) {
1688 // Step 5.e.i.
1689 if (desc.hasWritable() && desc.writable()) {
1690 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1691 }
1692
1693 // Step 5.e.ii.
1694 if (desc.hasValue()) {
1695 RootedValue currentValue(cx);
1696 if (!GetExistingDataProperty(cx, obj, id, prop, &currentValue)) {
1697 return false;
1698 }
1699
1700 bool same;
1701 if (!SameValue(cx, desc.value(), currentValue, &same)) {
1702 return false;
1703 }
1704 if (!same) {
1705 return result.fail(JSMSG_CANT_REDEFINE_PROP);
1706 }
1707 }
1708
1709 return result.succeed();
1710 }
1711 }
1712
1713 // Fill in desc.[[Configurable]] and desc.[[Enumerable]] if missing.
1714 if (!desc.hasConfigurable()) {
1715 desc.setConfigurable(attrs.configurable());
1716 }
1717 if (!desc.hasEnumerable()) {
1718 desc.setEnumerable(attrs.enumerable());
1719 }
1720
1721 // Step 6.
1722 if (desc.isDataDescriptor()) {
1723 // Fill in desc.[[Value]] and desc.[[Writable]].
1724 if (IsDataDescriptor(prop)) {
1725 if (!desc.hasValue()) {
1726 RootedValue currentValue(cx);
1727 if (!GetExistingDataProperty(cx, obj, id, prop, &currentValue)) {
1728 return false;
1729 }
1730
1731 desc.setValue(currentValue);
1732 }
1733 if (!desc.hasWritable()) {
1734 desc.setWritable(attrs.writable());
1735 }
1736 } else {
1737 if (!desc.hasValue()) {
1738 desc.setValue(UndefinedHandleValue);
1739 }
1740 if (!desc.hasWritable()) {
1741 desc.setWritable(false);
1742 }
1743 }
1744 } else if (desc.isAccessorDescriptor()) {
1745 // Fill in desc.[[Get]] and desc.[[Set]] from shape.
1746 if (IsAccessorDescriptor(prop)) {
1747 PropertyInfo propInfo = prop.propertyInfo();
1748 MOZ_ASSERT(propInfo.isAccessorProperty());
1749 MOZ_ASSERT(desc.isAccessorDescriptor());
1750
1751 if (!desc.hasGetter()) {
1752 desc.setGetter(obj->getGetter(propInfo));
1753 }
1754 if (!desc.hasSetter()) {
1755 desc.setSetter(obj->getSetter(propInfo));
1756 }
1757 } else {
1758 if (!desc.hasGetter()) {
1759 desc.setGetter(nullptr);
1760 }
1761 if (!desc.hasSetter()) {
1762 desc.setSetter(nullptr);
1763 }
1764 }
1765 } else {
1766 MOZ_ASSERT(desc.isGenericDescriptor());
1767
1768 // Fill in desc. A generic descriptor has none of these fields, so copy
1769 // everything from shape.
1770 MOZ_ASSERT(!desc.hasValue());
1771 MOZ_ASSERT(!desc.hasWritable());
1772 MOZ_ASSERT(!desc.hasGetter());
1773 MOZ_ASSERT(!desc.hasSetter());
1774 if (IsDataDescriptor(prop)) {
1775 RootedValue currentValue(cx);
1776 if (!GetExistingDataProperty(cx, obj, id, prop, &currentValue)) {
1777 return false;
1778 }
1779 desc.setValue(currentValue);
1780 desc.setWritable(attrs.writable());
1781 } else {
1782 PropertyInfo propInfo = prop.propertyInfo();
1783 desc.setGetter(obj->getGetter(propInfo));
1784 desc.setSetter(obj->getSetter(propInfo));
1785 }
1786 }
1787 desc.assertComplete();
1788
1789 if (!AddOrChangeProperty<IsAddOrChange::Change>(cx, obj, id, desc, &prop)) {
1790 return false;
1791 }
1792
1793 // Step 7.
1794 return result.succeed();
1795 }
1796
1797 bool js::NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1798 HandleId id, HandleValue value,
1799 unsigned attrs, ObjectOpResult& result) {
1800 Rooted<PropertyDescriptor> desc(cx, PropertyDescriptor::Data(value, attrs));
1801 return NativeDefineProperty(cx, obj, id, desc, result);
1802 }
1803
1804 bool js::NativeDefineAccessorProperty(JSContext* cx, Handle<NativeObject*> obj,
1805 HandleId id, HandleObject getter,
1806 HandleObject setter, unsigned attrs) {
1807 Rooted<PropertyDescriptor> desc(
1808 cx, PropertyDescriptor::Accessor(
1809 getter ? mozilla::Some(getter) : mozilla::Nothing(),
1810 setter ? mozilla::Some(setter) : mozilla::Nothing(), attrs));
1811
1812 ObjectOpResult result;
1813 if (!NativeDefineProperty(cx, obj, id, desc, result)) {
1814 return false;
1815 }
1816
1817 if (!result) {
1818 // Off-thread callers should not get here: they must call this
1819 // function only with known-valid arguments. Populating a new
1820 // PlainObject with configurable properties is fine.
1821 result.reportError(cx, obj, id);
1822 return false;
1823 }
1824
1825 return true;
1826 }
1827
1828 bool js::NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1829 HandleId id, HandleValue value,
1830 unsigned attrs) {
1831 ObjectOpResult result;
1832 if (!NativeDefineDataProperty(cx, obj, id, value, attrs, result)) {
1833 return false;
1834 }
1835 if (!result) {
1836 // Off-thread callers should not get here: they must call this
1837 // function only with known-valid arguments. Populating a new
1838 // PlainObject with configurable properties is fine.
1839 result.reportError(cx, obj, id);
1840 return false;
1841 }
1842 return true;
1843 }
1844
1845 bool js::NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1846 PropertyName* name, HandleValue value,
1847 unsigned attrs) {
1848 RootedId id(cx, NameToId(name));
1849 return NativeDefineDataProperty(cx, obj, id, value, attrs);
1850 }
1851
1852 static bool DefineNonexistentProperty(JSContext* cx, Handle<NativeObject*> obj,
1853 HandleId id, HandleValue v,
1854 ObjectOpResult& result) {
1855 // Optimized NativeDefineProperty() version for known absent properties.
1856
1857 // Dispense with custom behavior of exotic native objects first.
1858 if (obj->is<ArrayObject>()) {
1859 // Array's length property is non-configurable, so we shouldn't
1860 // encounter it in this function.
1861 MOZ_ASSERT(id != NameToId(cx->names().length));
1862
1863 // 10.4.2.1 step 2. Don't extend a fixed-length array.
1864 uint32_t index;
1865 if (IdIsIndex(id, &index)) {
1866 if (WouldDefinePastNonwritableLength(&obj->as<ArrayObject>(), index)) {
1867 return result.fail(JSMSG_CANT_DEFINE_PAST_ARRAY_LENGTH);
1868 }
1869 }
1870 } else if (obj->is<ArgumentsObject>()) {
1871 // If this method is called with either |length| or |@@iterator|, the
1872 // property was previously deleted and hence should already be marked
1873 // as overridden.
1874 MOZ_ASSERT_IF(id.isAtom(cx->names().length),
1875 obj->as<ArgumentsObject>().hasOverriddenLength());
1876 MOZ_ASSERT_IF(id.isWellKnownSymbol(JS::SymbolCode::iterator),
1877 obj->as<ArgumentsObject>().hasOverriddenIterator());
1878
1879 // We still need to mark any element properties as overridden.
1880 if (id.isInt()) {
1881 obj->as<ArgumentsObject>().markElementOverridden();
1882 }
1883 }
1884
1885 // Indexed properties of typed arrays are handled by the caller.
1886 MOZ_ASSERT_IF(obj->is<TypedArrayObject>(), ToTypedArrayIndex(id).isNothing());
1887
1888 #ifdef DEBUG
1889 PropertyResult prop;
1890 if (!NativeLookupOwnPropertyNoResolve(cx, obj, id, &prop)) {
1891 return false;
1892 }
1893 MOZ_ASSERT(prop.isNotFound(), "didn't expect to find an existing property");
1894 #endif
1895
1896 // 10.1.6.3, ValidateAndApplyPropertyDescriptor.
1897 // Step 1 is a redundant assertion, step 3 and later don't apply here.
1898
1899 // Step 2.
1900 if (!obj->isExtensible()) {
1901 return result.fail(JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE);
1902 }
1903
1904 if (id.isInt()) {
1905 // This might be a dense element. Use AddOrChangeProperty as it knows
1906 // how to deal with that.
1907 Rooted<PropertyDescriptor> desc(
1908 cx, PropertyDescriptor::Data(v, {JS::PropertyAttribute::Configurable,
1909 JS::PropertyAttribute::Enumerable,
1910 JS::PropertyAttribute::Writable}));
1911 if (!AddOrChangeProperty<IsAddOrChange::Add>(cx, obj, id, desc)) {
1912 return false;
1913 }
1914 } else {
1915 if (!AddDataProperty(cx, obj, id, v)) {
1916 return false;
1917 }
1918 }
1919
1920 return result.succeed();
1921 }
1922
1923 bool js::AddOrUpdateSparseElementHelper(JSContext* cx,
1924 Handle<NativeObject*> obj,
1925 int32_t int_id, HandleValue v,
1926 bool strict) {
1927 MOZ_ASSERT(obj->is<ArrayObject>() || obj->is<PlainObject>());
1928
1929 // This helper doesn't handle the case where the index is a dense element.
1930 MOZ_ASSERT(int_id >= 0);
1931 MOZ_ASSERT(!obj->containsDenseElement(int_id));
1932
1933 MOZ_ASSERT(PropertyKey::fitsInInt(int_id));
1934 RootedId id(cx, PropertyKey::Int(int_id));
1935
1936 // First decide if this is an add or an update. Because the IC guards have
1937 // already ensured this exists exterior to the dense array range, and the
1938 // prototype checks have ensured there are no indexes on the prototype, we
1939 // can use the shape lineage to find the element if it exists:
1940 uint32_t index;
1941 PropMap* map = obj->shape()->lookup(cx, id, &index);
1942
1943 // If we didn't find the property, we're on the add path: delegate to
1944 // AddOrChangeProperty. This will add either a sparse element or a dense
1945 // element.
1946 if (map == nullptr) {
1947 Rooted<PropertyDescriptor> desc(
1948 cx, PropertyDescriptor::Data(v, {JS::PropertyAttribute::Configurable,
1949 JS::PropertyAttribute::Enumerable,
1950 JS::PropertyAttribute::Writable}));
1951 return AddOrChangeProperty<IsAddOrChange::Add>(cx, obj, id, desc);
1952 }
1953
1954 // At this point we're updating a property: See SetExistingProperty.
1955 PropertyInfo prop = map->getPropertyInfo(index);
1956 if (prop.isDataProperty() && prop.writable()) {
1957 obj->setSlot(prop.slot(), v);
1958 return true;
1959 }
1960
1961 // We don't know exactly what this object looks like, hit the slowpath.
1962 RootedValue receiver(cx, ObjectValue(*obj));
1963 JS::ObjectOpResult result;
1964 return SetProperty(cx, obj, id, v, receiver, result) &&
1965 result.checkStrictModeError(cx, obj, id, strict);
1966 }
1967
1968 /*** [[HasProperty]] ********************************************************/
1969
1970 /**
1971 * 10.1.7.1 OrdinaryHasProperty ( O, P )
1972 *
1973 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
1974 */
1975 bool js::NativeHasProperty(JSContext* cx, Handle<NativeObject*> obj,
1976 HandleId id, bool* foundp) {
1977 Rooted<NativeObject*> pobj(cx, obj);
1978 PropertyResult prop;
1979
1980 // This loop isn't explicit in the spec algorithm. See the comment on step
1981 // 4.a. below.
1982 for (;;) {
1983 // Step 1.
1984 if (!NativeLookupOwnPropertyInline<CanGC>(cx, pobj, id, &prop)) {
1985 return false;
1986 }
1987
1988 // Step 2.
1989 if (prop.isFound()) {
1990 *foundp = true;
1991 return true;
1992 }
1993
1994 // Step 3.
1995 JSObject* proto = pobj->staticPrototype();
1996
1997 // Step 5. (Reordered)
1998 // As a side-effect of NativeLookupOwnPropertyInline, we may determine that
1999 // a property is not found and the proto chain should not be searched. This
2000 // can occur for:
2001 // - Out-of-range numeric properties of a TypedArrayObject
2002 // - Recursive resolve hooks (which is expected when they try to set the
2003 // property being resolved).
2004 if (!proto || prop.shouldIgnoreProtoChain()) {
2005 *foundp = false;
2006 return true;
2007 }
2008
2009 // Step 4.a. If the prototype is also native, this step is a recursive tail
2010 // call, and we don't need to go through all the plumbing of HasProperty;
2011 // the top of the loop is where we're going to end up anyway. But if |proto|
2012 // is non-native, that optimization would be incorrect.
2013 if (!proto->is<NativeObject>()) {
2014 RootedObject protoRoot(cx, proto);
2015 return HasProperty(cx, protoRoot, id, foundp);
2016 }
2017
2018 pobj = &proto->as<NativeObject>();
2019 }
2020 }
2021
2022 /*** [[GetOwnPropertyDescriptor]] *******************************************/
2023
2024 bool js::NativeGetOwnPropertyDescriptor(
2025 JSContext* cx, Handle<NativeObject*> obj, HandleId id,
2026 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
2027 PropertyResult prop;
2028 if (!NativeLookupOwnProperty<CanGC>(cx, obj, id, &prop)) {
2029 return false;
2030 }
2031 if (prop.isNotFound()) {
2032 desc.reset();
2033 return true;
2034 }
2035
2036 if (prop.isNativeProperty() && prop.propertyInfo().isAccessorProperty()) {
2037 PropertyInfo propInfo = prop.propertyInfo();
2038 desc.set(mozilla::Some(PropertyDescriptor::Accessor(
2039 obj->getGetter(propInfo), obj->getSetter(propInfo),
2040 propInfo.propAttributes())));
2041 return true;
2042 }
2043
2044 RootedValue value(cx);
2045 if (!GetExistingDataProperty(cx, obj, id, prop, &value)) {
2046 return false;
2047 }
2048
2049 JS::PropertyAttributes attrs = GetPropertyAttributes(obj, prop);
2050 desc.set(mozilla::Some(PropertyDescriptor::Data(value, attrs)));
2051 return true;
2052 }
2053
2054 /*** [[Get]] ****************************************************************/
2055
2056 static bool GetCustomDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2057 MutableHandleValue vp) {
2058 cx->check(obj, id, vp);
2059
2060 const JSClass* clasp = obj->getClass();
2061 if (clasp == &ArrayObject::class_) {
2062 if (!ArrayLengthGetter(cx, obj, id, vp)) {
2063 return false;
2064 }
2065 } else if (clasp == &MappedArgumentsObject::class_) {
2066 if (!MappedArgGetter(cx, obj, id, vp)) {
2067 return false;
2068 }
2069 } else {
2070 MOZ_RELEASE_ASSERT(clasp == &UnmappedArgumentsObject::class_);
2071 if (!UnmappedArgGetter(cx, obj, id, vp)) {
2072 return false;
2073 }
2074 }
2075
2076 cx->check(vp);
2077 return true;
2078 }
2079
2080 static inline bool CallGetter(JSContext* cx, Handle<NativeObject*> obj,
2081 HandleValue receiver, HandleId id,
2082 PropertyInfo prop, MutableHandleValue vp) {
2083 MOZ_ASSERT(!prop.isDataProperty());
2084
2085 if (prop.isAccessorProperty()) {
2086 RootedValue getter(cx, obj->getGetterValue(prop));
2087 return js::CallGetter(cx, receiver, getter, vp);
2088 }
2089
2090 MOZ_ASSERT(prop.isCustomDataProperty());
2091
2092 return GetCustomDataProperty(cx, obj, id, vp);
2093 }
2094
2095 template <AllowGC allowGC>
2096 static MOZ_ALWAYS_INLINE bool GetExistingProperty(
2097 JSContext* cx, typename MaybeRooted<Value, allowGC>::HandleType receiver,
2098 typename MaybeRooted<NativeObject*, allowGC>::HandleType obj,
2099 typename MaybeRooted<jsid, allowGC>::HandleType id, PropertyInfo prop,
2100 typename MaybeRooted<Value, allowGC>::MutableHandleType vp) {
2101 if (prop.isDataProperty()) {
2102 vp.set(obj->getSlot(prop.slot()));
2103 return true;
2104 }
2105
2106 vp.setUndefined();
2107
2108 if (!prop.isCustomDataProperty() && !obj->hasGetter(prop)) {
2109 return true;
2110 }
2111
2112 if constexpr (!allowGC) {
2113 return false;
2114 } else {
2115 return CallGetter(cx, obj, receiver, id, prop, vp);
2116 }
2117 }
2118
2119 bool js::NativeGetExistingProperty(JSContext* cx, HandleObject receiver,
2120 Handle<NativeObject*> obj, HandleId id,
2121 PropertyInfo prop, MutableHandleValue vp) {
2122 RootedValue receiverValue(cx, ObjectValue(*receiver));
2123 return GetExistingProperty<CanGC>(cx, receiverValue, obj, id, prop, vp);
2124 }
2125
2126 enum IsNameLookup { NotNameLookup = false, NameLookup = true };
2127
2128 /*
2129 * Finish getting the property `receiver[id]` after looking at every object on
2130 * the prototype chain and not finding any such property.
2131 *
2132 * Per the spec, this should just set the result to `undefined` and call it a
2133 * day. However this function also runs when we're evaluating an
2134 * expression that's an Identifier (that is, an unqualified name lookup),
2135 * so we need to figure out if that's what's happening and throw
2136 * a ReferenceError if so.
2137 */
2138 static bool GetNonexistentProperty(JSContext* cx, HandleId id,
2139 IsNameLookup nameLookup,
2140 MutableHandleValue vp) {
2141 vp.setUndefined();
2142
2143 // If we are doing a name lookup, this is a ReferenceError.
2144 if (nameLookup) {
2145 ReportIsNotDefined(cx, id);
2146 return false;
2147 }
2148
2149 // Otherwise, just return |undefined|.
2150 return true;
2151 }
2152
2153 // The NoGC version of GetNonexistentProperty, present only to make types line
2154 // up.
2155 bool GetNonexistentProperty(JSContext* cx, const jsid& id,
2156 IsNameLookup nameLookup,
2157 FakeMutableHandle<Value> vp) {
2158 return false;
2159 }
2160
2161 static inline bool GeneralizedGetProperty(JSContext* cx, HandleObject obj,
2162 HandleId id, HandleValue receiver,
2163 IsNameLookup nameLookup,
2164 MutableHandleValue vp) {
2165 AutoCheckRecursionLimit recursion(cx);
2166 if (!recursion.check(cx)) {
2167 return false;
2168 }
2169 if (nameLookup) {
2170 // When nameLookup is true, GeneralizedGetProperty implements 9.1.1.2.6
2171 // GetBindingValue, ES2025 rev ac21460fedf4b926520b06c9820bdbebad596a8b,
2172 // with step 2 (the call to HasProperty) and step 4 (the call to Get) fused
2173 // so that only a single lookup is needed.
2174 //
2175 // If we get here, we've reached a non-native object. Fall back on the
2176 // algorithm as specified, with two separate lookups. (Note that we
2177 // throw ReferenceErrors regardless of strictness, technically a bug.)
2178
2179 bool found;
2180 if (!HasProperty(cx, obj, id, &found)) {
2181 return false;
2182 }
2183 if (!found) {
2184 ReportIsNotDefined(cx, id);
2185 return false;
2186 }
2187 }
2188
2189 return GetProperty(cx, obj, receiver, id, vp);
2190 }
2191
2192 static inline bool GeneralizedGetProperty(JSContext* cx, JSObject* obj, jsid id,
2193 const Value& receiver,
2194 IsNameLookup nameLookup,
2195 FakeMutableHandle<Value> vp) {
2196 AutoCheckRecursionLimit recursion(cx);
2197 if (!recursion.checkDontReport(cx)) {
2198 return false;
2199 }
2200 if (nameLookup) {
2201 return false;
2202 }
2203 return GetPropertyNoGC(cx, obj, receiver, id, vp.address());
2204 }
2205
2206 bool js::GetSparseElementHelper(JSContext* cx, Handle<NativeObject*> obj,
2207 int32_t int_id, MutableHandleValue result) {
2208 MOZ_ASSERT(obj->is<ArrayObject>() || obj->is<PlainObject>());
2209
2210 // This helper doesn't handle the case where the index is a dense element.
2211 MOZ_ASSERT(int_id >= 0);
2212 MOZ_ASSERT(!obj->containsDenseElement(int_id));
2213
2214 // Indexed properties can not exist on the prototype chain.
2215 MOZ_ASSERT(!PrototypeMayHaveIndexedProperties(obj));
2216
2217 MOZ_ASSERT(PropertyKey::fitsInInt(int_id));
2218 RootedId id(cx, PropertyKey::Int(int_id));
2219
2220 uint32_t index;
2221 PropMap* map = obj->shape()->lookup(cx, id, &index);
2222 if (!map) {
2223 // Property not found, return directly.
2224 result.setUndefined();
2225 return true;
2226 }
2227
2228 PropertyInfo prop = map->getPropertyInfo(index);
2229 RootedValue receiver(cx, ObjectValue(*obj));
2230 return GetExistingProperty<CanGC>(cx, receiver, obj, id, prop, result);
2231 }
2232
2233 /**
2234 * 10.1.8.1 OrdinaryGet ( O, P, Receiver )
2235 *
2236 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2237 */
2238 template <AllowGC allowGC>
2239 static MOZ_ALWAYS_INLINE bool NativeGetPropertyInline(
2240 JSContext* cx, typename MaybeRooted<NativeObject*, allowGC>::HandleType obj,
2241 typename MaybeRooted<Value, allowGC>::HandleType receiver,
2242 typename MaybeRooted<jsid, allowGC>::HandleType id, IsNameLookup nameLookup,
2243 typename MaybeRooted<Value, allowGC>::MutableHandleType vp) {
2244 typename MaybeRooted<NativeObject*, allowGC>::RootType pobj(cx, obj);
2245 PropertyResult prop;
2246
2247 // This loop isn't explicit in the spec algorithm. See the comment on step
2248 // 2.c below.
2249 for (;;) {
2250 // Step 1.
2251 if (!NativeLookupOwnPropertyInline<allowGC>(cx, pobj, id, &prop)) {
2252 return false;
2253 }
2254
2255 if (prop.isFound()) {
2256 // Steps 3-7. Special case for dense elements because
2257 // GetExistingProperty doesn't support those.
2258 if (prop.isDenseElement()) {
2259 vp.set(pobj->getDenseElement(prop.denseElementIndex()));
2260 return true;
2261 }
2262 if (prop.isTypedArrayElement()) {
2263 size_t idx = prop.typedArrayElementIndex();
2264 auto* tarr = &pobj->template as<TypedArrayObject>();
2265 return tarr->template getElement<allowGC>(cx, idx, vp);
2266 }
2267
2268 return GetExistingProperty<allowGC>(cx, receiver, pobj, id,
2269 prop.propertyInfo(), vp);
2270 }
2271
2272 // Step 2.a.
2273 JSObject* proto = pobj->staticPrototype();
2274
2275 // Step 2.b. The spec algorithm simply returns undefined if proto is
2276 // null, but see the comment on GetNonexistentProperty.
2277 if (!proto || prop.shouldIgnoreProtoChain()) {
2278 return GetNonexistentProperty(cx, id, nameLookup, vp);
2279 }
2280
2281 // Step 2. If the prototype is also native, this step is a recursive tail
2282 // call, and we don't need to go through all the plumbing of GetProperty;
2283 // the top of the loop is where we're going to end up anyway. But if |proto|
2284 // is non-native, that optimization would be incorrect.
2285 if (proto->getOpsGetProperty()) {
2286 RootedObject protoRoot(cx, proto);
2287 return GeneralizedGetProperty(cx, protoRoot, id, receiver, nameLookup,
2288 vp);
2289 }
2290
2291 pobj = &proto->as<NativeObject>();
2292 }
2293 }
2294
2295 bool js::NativeGetProperty(JSContext* cx, Handle<NativeObject*> obj,
2296 HandleValue receiver, HandleId id,
2297 MutableHandleValue vp) {
2298 return NativeGetPropertyInline<CanGC>(cx, obj, receiver, id, NotNameLookup,
2299 vp);
2300 }
2301
2302 bool js::NativeGetPropertyNoGC(JSContext* cx, NativeObject* obj,
2303 const Value& receiver, jsid id, Value* vp) {
2304 AutoAssertNoPendingException noexc(cx);
2305 return NativeGetPropertyInline<NoGC>(cx, obj, receiver, id, NotNameLookup,
2306 vp);
2307 }
2308
2309 bool js::NativeGetElement(JSContext* cx, Handle<NativeObject*> obj,
2310 HandleValue receiver, int32_t index,
2311 MutableHandleValue vp) {
2312 RootedId id(cx);
2313
2314 if (MOZ_LIKELY(index >= 0)) {
2315 if (!IndexToId(cx, index, &id)) {
2316 return false;
2317 }
2318 } else {
2319 RootedValue indexVal(cx, Int32Value(index));
2320 if (!PrimitiveValueToId<CanGC>(cx, indexVal, &id)) {
2321 return false;
2322 }
2323 }
2324 return NativeGetProperty(cx, obj, receiver, id, vp);
2325 }
2326
2327 bool js::GetNameBoundInEnvironment(JSContext* cx, HandleObject envArg,
2328 HandleId id, MutableHandleValue vp) {
2329 // Manually unwrap 'with' environments to prevent looking up @@unscopables
2330 // twice.
2331 //
2332 // This is unfortunate because internally, the engine does not distinguish
2333 // HasProperty from HasBinding: both are implemented as a HasPropertyOp
2334 // hook on a WithEnvironmentObject.
2335 //
2336 // In the case of attempting to get the value of a binding already looked up
2337 // via JSOp::BindName or JSOp::BindUnqualifiedName, calling HasProperty on the
2338 // WithEnvironmentObject is equivalent to calling HasBinding a second time.
2339 // This results in the incorrect behavior of performing the @@unscopables
2340 // check again.
2341 RootedObject env(cx, MaybeUnwrapWithEnvironment(envArg));
2342 RootedValue receiver(cx, ObjectValue(*env));
2343 if (env->getOpsGetProperty()) {
2344 return GeneralizedGetProperty(cx, env, id, receiver, NameLookup, vp);
2345 }
2346 return NativeGetPropertyInline<CanGC>(cx, env.as<NativeObject>(), receiver,
2347 id, NameLookup, vp);
2348 }
2349
2350 /*** [[Set]] ****************************************************************/
2351
2352 static bool SetCustomDataProperty(JSContext* cx, HandleObject obj, HandleId id,
2353 HandleValue v, ObjectOpResult& result) {
2354 cx->check(obj, id, v);
2355
2356 const JSClass* clasp = obj->getClass();
2357 if (clasp == &ArrayObject::class_) {
2358 return ArrayLengthSetter(cx, obj, id, v, result);
2359 }
2360 if (clasp == &MappedArgumentsObject::class_) {
2361 return MappedArgSetter(cx, obj, id, v, result);
2362 }
2363 MOZ_RELEASE_ASSERT(clasp == &UnmappedArgumentsObject::class_);
2364 return UnmappedArgSetter(cx, obj, id, v, result);
2365 }
2366
2367 static bool MaybeReportUndeclaredVarAssignment(JSContext* cx, HandleId id) {
2368 {
2369 jsbytecode* pc;
2370 JSScript* script =
2371 cx->currentScript(&pc, JSContext::AllowCrossRealm::Allow);
2372 if (!script) {
2373 return true;
2374 }
2375
2376 if (!IsStrictSetPC(pc)) {
2377 return true;
2378 }
2379 }
2380
2381 UniqueChars bytes =
2382 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsIdentifier);
2383 if (!bytes) {
2384 return false;
2385 }
2386 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_UNDECLARED_VAR,
2387 bytes.get());
2388 return false;
2389 }
2390
2391 /*
2392 * Finish assignment to a shapeful data property of a native object obj. This
2393 * conforms to no standard and there is a lot of legacy baggage here.
2394 */
2395 static bool NativeSetExistingDataProperty(JSContext* cx,
2396 Handle<NativeObject*> obj,
2397 HandleId id, PropertyInfo prop,
2398 HandleValue v,
2399 ObjectOpResult& result) {
2400 MOZ_ASSERT(obj->is<NativeObject>());
2401 MOZ_ASSERT(prop.isDataDescriptor());
2402
2403 Watchtower::watchPropertyValueChange<AllowGC::CanGC>(cx, obj, id, v, prop);
2404
2405 if (prop.isDataProperty()) {
2406 // The common path. Standard data property.
2407 obj->setSlot(prop.slot(), v);
2408 return result.succeed();
2409 }
2410
2411 MOZ_ASSERT(prop.isCustomDataProperty());
2412 MOZ_ASSERT(!obj->is<WithEnvironmentObject>()); // See bug 1128681.
2413
2414 return SetCustomDataProperty(cx, obj, id, v, result);
2415 }
2416
2417 /**
2418 * 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc )
2419 *
2420 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2421 *
2422 * When a [[Set]] operation finds no existing property with the given id
2423 * or finds a writable data property on the prototype chain, we end up here.
2424 * Finish the [[Set]] by defining a new property on receiver.
2425 *
2426 * This implements steps 2.b-e, but it is really old code and there are a few
2427 * barnacles.
2428 */
2429 static bool SetPropertyByDefining(JSContext* cx, HandleId id, HandleValue v,
2430 HandleValue receiverValue,
2431 ObjectOpResult& result) {
2432 // Step 2.b.
2433 if (!receiverValue.isObject()) {
2434 return result.fail(JSMSG_SET_NON_OBJECT_RECEIVER);
2435 }
2436 RootedObject receiver(cx, &receiverValue.toObject());
2437
2438 bool existing;
2439 {
2440 // Step 2.c.
2441 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
2442 if (!GetOwnPropertyDescriptor(cx, receiver, id, &desc)) {
2443 return false;
2444 }
2445
2446 existing = desc.isSome();
2447
2448 // Step 2.d.
2449 if (existing) {
2450 // Step 2.d.i.
2451 if (desc->isAccessorDescriptor()) {
2452 return result.fail(JSMSG_OVERWRITING_ACCESSOR);
2453 }
2454
2455 // Step 2.d.ii.
2456 if (!desc->writable()) {
2457 return result.fail(JSMSG_READ_ONLY);
2458 }
2459 }
2460 }
2461
2462 // Steps 2.d.iii-iv. and 2.e.i. Define the new data property.
2463 Rooted<PropertyDescriptor> desc(cx);
2464 if (existing) {
2465 desc = PropertyDescriptor::Empty();
2466 desc.setValue(v);
2467 } else {
2468 desc = PropertyDescriptor::Data(v, {JS::PropertyAttribute::Configurable,
2469 JS::PropertyAttribute::Enumerable,
2470 JS::PropertyAttribute::Writable});
2471 }
2472 return DefineProperty(cx, receiver, id, desc, result);
2473 }
2474
2475 enum class TypedArrayOutOfRange : bool { No, Yes };
2476
2477 /**
2478 * 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc )
2479 * 10.4.5.5 [[Set]] ( P, V, Receiver )
2480 *
2481 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2482 *
2483 * Implement "the rest of" assignment to a property when no property
2484 * receiver[id] was found anywhere on the prototype chain.
2485 */
2486 template <QualifiedBool IsQualified>
2487 static bool SetNonexistentProperty(JSContext* cx, Handle<NativeObject*> obj,
2488 Handle<NativeObject*> pobj, HandleId id,
2489 HandleValue v, HandleValue receiver,
2490 TypedArrayOutOfRange typedArrayOutOfRange,
2491 ObjectOpResult& result) {
2492 if (!IsQualified && receiver.isObject() &&
2493 receiver.toObject().isUnqualifiedVarObj()) {
2494 if (!MaybeReportUndeclaredVarAssignment(cx, id)) {
2495 return false;
2496 }
2497 }
2498
2499 // Unqualified access may also need to take this code path, but it's currently
2500 // hard to tell, because with-environment objects call SetProperty<Qualified>,
2501 // which seems a bit dubious. And other environment objects probably don't
2502 // have typed array objects in the middle of their prototype chain, so we
2503 // can't really test this code path without first fixing with-environments.
2504 if constexpr (IsQualified) {
2505 // Indexed properties of typed arrays are special.
2506 if (typedArrayOutOfRange == TypedArrayOutOfRange::Yes) {
2507 MOZ_ASSERT(pobj->is<TypedArrayObject>(),
2508 "typed array out-of-range reported by non-typed array?");
2509 MOZ_ASSERT(pobj == obj || !obj->is<TypedArrayObject>(),
2510 "prototype chain not traversed for typed array indices");
2511
2512 // 10.4.5.5, step 1.b.i.
2513 if (receiver.isObject() && pobj == &receiver.toObject()) {
2514 mozilla::Maybe<uint64_t> index = ToTypedArrayIndex(id);
2515 MOZ_ASSERT(index, "typed array out-of-range reported by non-index?");
2516
2517 auto tobj = HandleObject(pobj).as<TypedArrayObject>();
2518 return SetTypedArrayElement(cx, tobj, *index, v, result);
2519 }
2520
2521 // 10.4.5.5, step 1.b.ii.
2522 return result.succeed();
2523 }
2524 }
2525
2526 // Pure optimization for the common case. There's no point performing the
2527 // lookup in step 2.c again, as our caller just did it for us.
2528 if (IsQualified && receiver.isObject() && obj == &receiver.toObject()) {
2529 // Ensure that a custom GetOwnPropertyOp, if present, doesn't
2530 // introduce additional properties which weren't previously found by
2531 // LookupOwnProperty.
2532 #ifdef DEBUG
2533 if (GetOwnPropertyOp op = obj->getOpsGetOwnPropertyDescriptor()) {
2534 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
2535 if (!op(cx, obj, id, &desc)) {
2536 return false;
2537 }
2538 MOZ_ASSERT(desc.isNothing());
2539 }
2540 #endif
2541
2542 // Step 2.e. Define the new data property.
2543 if (DefinePropertyOp op = obj->getOpsDefineProperty()) {
2544 Rooted<PropertyDescriptor> desc(
2545 cx, PropertyDescriptor::Data(v, {JS::PropertyAttribute::Configurable,
2546 JS::PropertyAttribute::Enumerable,
2547 JS::PropertyAttribute::Writable}));
2548 return op(cx, obj, id, desc, result);
2549 }
2550
2551 return DefineNonexistentProperty(cx, obj, id, v, result);
2552 }
2553
2554 return SetPropertyByDefining(cx, id, v, receiver, result);
2555 }
2556
2557 // Set an existing own property obj[index] that's a dense element.
2558 static bool SetDenseElement(JSContext* cx, Handle<NativeObject*> obj,
2559 uint32_t index, HandleValue v,
2560 ObjectOpResult& result) {
2561 MOZ_ASSERT(!obj->is<TypedArrayObject>());
2562 MOZ_ASSERT(obj->containsDenseElement(index));
2563
2564 obj->setDenseElement(index, v);
2565 return result.succeed();
2566 }
2567
2568 /**
2569 * 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc )
2570 *
2571 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2572 *
2573 * Finish the assignment `receiver[id] = v` when an existing property |prop|
2574 * has been found on a native object |pobj|.
2575 *
2576 * It is necessary to pass both id and prop because prop could be an implicit
2577 * dense or typed array element (i.e. not actually a pointer to a Shape).
2578 */
2579 static bool SetExistingProperty(JSContext* cx, HandleId id, HandleValue v,
2580 HandleValue receiver,
2581 Handle<NativeObject*> pobj,
2582 const PropertyResult& prop,
2583 ObjectOpResult& result) {
2584 // Step 1. (Performed in caller)
2585
2586 // Step 2 for dense and typed array elements.
2587 if (prop.isDenseElement() || prop.isTypedArrayElement()) {
2588 // Step 2.a.
2589 if (pobj->denseElementsAreFrozen()) {
2590 return result.fail(JSMSG_READ_ONLY);
2591 }
2592
2593 // Pure optimization for the common case:
2594 if (receiver.isObject() && pobj == &receiver.toObject()) {
2595 if (prop.isTypedArrayElement()) {
2596 Rooted<TypedArrayObject*> tobj(cx, &pobj->as<TypedArrayObject>());
2597 size_t idx = prop.typedArrayElementIndex();
2598 return SetTypedArrayElement(cx, tobj, idx, v, result);
2599 }
2600
2601 return SetDenseElement(cx, pobj, prop.denseElementIndex(), v, result);
2602 }
2603
2604 // Steps 2.b-e.
2605 return SetPropertyByDefining(cx, id, v, receiver, result);
2606 }
2607
2608 // Step 2 for all other properties.
2609 PropertyInfo propInfo = prop.propertyInfo();
2610 if (propInfo.isDataDescriptor()) {
2611 // Step 2.a.
2612 if (!propInfo.writable()) {
2613 return result.fail(JSMSG_READ_ONLY);
2614 }
2615
2616 // steps 2.c-d.
2617 if (receiver.isObject() && pobj == &receiver.toObject()) {
2618 // Pure optimization for the common case. There's no point performing
2619 // the lookup in step 2.c again, as our caller just did it for us. The
2620 // result is |shapeProp|.
2621
2622 // Steps 2.d.iii-iv.
2623 return NativeSetExistingDataProperty(cx, pobj, id, propInfo, v, result);
2624 }
2625
2626 // Shadow pobj[id] by defining a new data property receiver[id].
2627 // Delegate everything to SetPropertyByDefining.
2628 return SetPropertyByDefining(cx, id, v, receiver, result);
2629 }
2630
2631 // Step 3.
2632 MOZ_ASSERT(propInfo.isAccessorProperty());
2633
2634 // Step 4.
2635 JSObject* setterObject = pobj->getSetter(propInfo);
2636
2637 // Step 5.
2638 if (!setterObject) {
2639 return result.fail(JSMSG_GETTER_ONLY);
2640 }
2641
2642 // Step 6.
2643 RootedValue setter(cx, ObjectValue(*setterObject));
2644 if (!js::CallSetter(cx, receiver, setter, v)) {
2645 return false;
2646 }
2647
2648 // Step 7.
2649 return result.succeed();
2650 }
2651
2652 /**
2653 * 10.1.9 [[Set]] ( P, V, Receiver )
2654 * 10.1.9.1 OrdinarySet ( O, P, V, Receiver )
2655 * 10.1.9.2 OrdinarySetWithOwnDescriptor ( O, P, V, Receiver, ownDesc )
2656 *
2657 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2658 */
2659 template <QualifiedBool IsQualified>
2660 bool js::NativeSetProperty(JSContext* cx, Handle<NativeObject*> obj,
2661 HandleId id, HandleValue v, HandleValue receiver,
2662 ObjectOpResult& result) {
2663 // We substitute our own names for these names used in the spec:
2664 // O -> pobj, P -> id, ownDesc -> prop.
2665 PropertyResult prop;
2666 Rooted<NativeObject*> pobj(cx, obj);
2667
2668 // This loop isn't explicit in the spec algorithm. See the comment on step
2669 // 1.b.i below. (There's a very similar loop in the NativeGetProperty
2670 // implementation, but unfortunately not similar enough to common up.)
2671 for (;;) {
2672 // OrdinarySet, step 1.
2673 if (!NativeLookupOwnPropertyInline<CanGC>(cx, pobj, id, &prop)) {
2674 return false;
2675 }
2676
2677 // OrdinarySetWithOwnDescriptor, steps 2-3.
2678 if (prop.isFound()) {
2679 return SetExistingProperty(cx, id, v, receiver, pobj, prop, result);
2680 }
2681
2682 // OrdinarySetWithOwnDescriptor, steps 1.a-b.
2683 // As a side-effect of NativeLookupOwnPropertyInline, we may determine that
2684 // a property is not found and the proto chain should not be searched. This
2685 // can occur for:
2686 // - Out-of-range numeric properties of a TypedArrayObject
2687 // - Recursive resolve hooks (which is expected when they try to set the
2688 // property being resolved).
2689 JSObject* proto = pobj->staticPrototype();
2690 if (!proto || prop.shouldIgnoreProtoChain()) {
2691 // OrdinarySetWithOwnDescriptor, step 1.c.i (and step 2).
2692 return SetNonexistentProperty<IsQualified>(
2693 cx, obj, pobj, id, v, receiver,
2694 TypedArrayOutOfRange{prop.isTypedArrayOutOfRange()}, result);
2695 }
2696
2697 // Step 1.b.i. If the prototype is also native, this step is a recursive
2698 // tail call, and we don't need to go through all the plumbing of
2699 // SetProperty; the top of the loop is where we're going to end up anyway.
2700 // But if |proto| is non-native, that optimization would be incorrect.
2701 if (!proto->is<NativeObject>()) {
2702 // Unqualified assignments are not specified to go through [[Set]]
2703 // at all, but they do go through this function. So check for
2704 // unqualified assignment to a nonexistent global (a strict error).
2705 RootedObject protoRoot(cx, proto);
2706 if (!IsQualified) {
2707 bool found;
2708 if (!HasProperty(cx, protoRoot, id, &found)) {
2709 return false;
2710 }
2711 if (!found) {
2712 return SetNonexistentProperty<IsQualified>(
2713 cx, obj, pobj, id, v, receiver, TypedArrayOutOfRange::No, result);
2714 }
2715 }
2716
2717 return SetProperty(cx, protoRoot, id, v, receiver, result);
2718 }
2719 pobj = &proto->as<NativeObject>();
2720 }
2721 }
2722
2723 template bool js::NativeSetProperty<Qualified>(JSContext* cx,
2724 Handle<NativeObject*> obj,
2725 HandleId id, HandleValue value,
2726 HandleValue receiver,
2727 ObjectOpResult& result);
2728
2729 template bool js::NativeSetProperty<Unqualified>(JSContext* cx,
2730 Handle<NativeObject*> obj,
2731 HandleId id, HandleValue value,
2732 HandleValue receiver,
2733 ObjectOpResult& result);
2734
2735 bool js::NativeSetElement(JSContext* cx, Handle<NativeObject*> obj,
2736 uint32_t index, HandleValue v, HandleValue receiver,
2737 ObjectOpResult& result) {
2738 RootedId id(cx);
2739 if (!IndexToId(cx, index, &id)) {
2740 return false;
2741 }
2742 return NativeSetProperty<Qualified>(cx, obj, id, v, receiver, result);
2743 }
2744
2745 /*** [[Delete]] *************************************************************/
2746
2747 static bool CallJSDeletePropertyOp(JSContext* cx, JSDeletePropertyOp op,
2748 HandleObject receiver, HandleId id,
2749 ObjectOpResult& result) {
2750 AutoCheckRecursionLimit recursion(cx);
2751 if (!recursion.check(cx)) {
2752 return false;
2753 }
2754
2755 cx->check(receiver, id);
2756 if (op) {
2757 return op(cx, receiver, id, result);
2758 }
2759 return result.succeed();
2760 }
2761
2762 /**
2763 * 10.1.10.1 OrdinaryDelete ( O, P )
2764 *
2765 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
2766 */
2767 bool js::NativeDeleteProperty(JSContext* cx, Handle<NativeObject*> obj,
2768 HandleId id, ObjectOpResult& result) {
2769 // Step 1.
2770 PropertyResult prop;
2771 if (!NativeLookupOwnProperty<CanGC>(cx, obj, id, &prop)) {
2772 return false;
2773 }
2774
2775 // Step 2.
2776 if (prop.isNotFound()) {
2777 // If no property call the class's delProperty hook, passing succeeded
2778 // as the result parameter. This always succeeds when there is no hook.
2779 return CallJSDeletePropertyOp(cx, obj->getClass()->getDelProperty(), obj,
2780 id, result);
2781 }
2782
2783 // Step 4. (Reordered) Non-configurable property.
2784 if (!GetPropertyAttributes(obj, prop).configurable()) {
2785 return result.failCantDelete();
2786 }
2787
2788 // Typed array elements are configurable, but can't be deleted.
2789 if (prop.isTypedArrayElement()) {
2790 return result.failCantDelete();
2791 }
2792
2793 if (!CallJSDeletePropertyOp(cx, obj->getClass()->getDelProperty(), obj, id,
2794 result)) {
2795 return false;
2796 }
2797 if (!result) {
2798 return true;
2799 }
2800
2801 // Step 3.
2802 if (prop.isDenseElement()) {
2803 obj->setDenseElementHole(prop.denseElementIndex());
2804 } else {
2805 if (!NativeObject::removeProperty(cx, obj, id)) {
2806 return false;
2807 }
2808 }
2809
2810 return SuppressDeletedProperty(cx, obj, id);
2811 }
2812
2813 bool js::CopyDataPropertiesNative(JSContext* cx, Handle<PlainObject*> target,
2814 Handle<NativeObject*> from,
2815 Handle<PlainObject*> excludedItems,
2816 bool* optimized) {
2817 *optimized = false;
2818
2819 // Don't use the fast path if |from| may have extra indexed or lazy
2820 // properties.
2821 if (from->getDenseInitializedLength() > 0 || from->isIndexed() ||
2822 from->is<TypedArrayObject>() || from->getClass()->getNewEnumerate() ||
2823 from->getClass()->getEnumerate()) {
2824 return true;
2825 }
2826
2827 // Collect all enumerable data properties.
2828 Rooted<PropertyInfoWithKeyVector> props(cx, PropertyInfoWithKeyVector(cx));
2829
2830 Rooted<NativeShape*> fromShape(cx, from->shape());
2831 for (ShapePropertyIter<NoGC> iter(fromShape); !iter.done(); iter++) {
2832 jsid id = iter->key();
2833 MOZ_ASSERT(!id.isInt());
2834
2835 if (!iter->enumerable()) {
2836 continue;
2837 }
2838 if (excludedItems && excludedItems->contains(cx, id)) {
2839 continue;
2840 }
2841
2842 // Don't use the fast path if |from| contains non-data properties.
2843 //
2844 // This enables two optimizations:
2845 // 1. We don't need to handle the case when accessors modify |from|.
2846 // 2. String and symbol properties can be added in one go.
2847 if (!iter->isDataProperty()) {
2848 return true;
2849 }
2850
2851 if (!props.append(*iter)) {
2852 return false;
2853 }
2854 }
2855
2856 *optimized = true;
2857
2858 // If |target| contains no own properties, we can directly call
2859 // AddDataPropertyNonPrototype.
2860 const bool targetHadNoOwnProperties = target->empty();
2861
2862 RootedId key(cx);
2863 RootedValue value(cx);
2864 for (size_t i = props.length(); i > 0; i--) {
2865 PropertyInfoWithKey prop = props[i - 1];
2866 MOZ_ASSERT(prop.isDataProperty());
2867 MOZ_ASSERT(prop.enumerable());
2868
2869 key = prop.key();
2870 MOZ_ASSERT(!key.isInt());
2871
2872 MOZ_ASSERT(from->is<NativeObject>());
2873 MOZ_ASSERT(from->shape() == fromShape);
2874
2875 value = from->getSlot(prop.slot());
2876 if (targetHadNoOwnProperties) {
2877 MOZ_ASSERT(!target->containsPure(key),
2878 "didn't expect to find an existing property");
2879
2880 if (!AddDataPropertyToPlainObject(cx, target, key, value)) {
2881 return false;
2882 }
2883 } else {
2884 if (!NativeDefineDataProperty(cx, target, key, value, JSPROP_ENUMERATE)) {
2885 return false;
2886 }
2887 }
2888 }
2889
2890 return true;
2891 }