Debian Codegraph @

js/src/vm/NativeObject.h

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 #ifndef vm_NativeObject_h
8 #define vm_NativeObject_h
9
10 #include "mozilla/Assertions.h"
11 #include "mozilla/Attributes.h"
12 #include "mozilla/Maybe.h"
13
14 #include <algorithm>
15 #include <stdint.h>
16
17 #include "NamespaceImports.h"
18
19 #include "gc/Barrier.h"
20 #include "gc/BufferAllocator.h"
21 #include "gc/MaybeRooted.h"
22 #include "gc/ZoneAllocator.h"
23 #include "js/shadow/Object.h" // JS::shadow::Object
24 #include "js/shadow/Zone.h" // JS::shadow::Zone
25 #include "js/Value.h"
26 #include "vm/GetterSetter.h"
27 #include "vm/JSAtomUtils.h" // AtomIsMarked
28 #include "vm/JSObject.h"
29 #include "vm/Shape.h"
30 #include "vm/StringType.h"
31
32 namespace js {
33
34 class JS_PUBLIC_API GenericPrinter;
35 class PropertyResult;
36
37 namespace gc {
38 class TenuringTracer;
39 } // namespace gc
40
41 /*
42 * To really poison a set of values, using 'magic' or 'undefined' isn't good
43 * enough since often these will just be ignored by buggy code (see bug 629974)
44 * in debug builds and crash in release builds. Instead, we use a safe-for-crash
45 * pointer.
46 */
47 static MOZ_ALWAYS_INLINE void Debug_SetValueRangeToCrashOnTouch(Value* beg,
48 Value* end) {
49 #ifdef DEBUG
50 for (Value* v = beg; v != end; ++v) {
51 *v = js::PoisonedObjectValue(0x48);
52 }
53 #endif
54 }
55
56 static MOZ_ALWAYS_INLINE void Debug_SetValueRangeToCrashOnTouch(Value* vec,
57 size_t len) {
58 #ifdef DEBUG
59 Debug_SetValueRangeToCrashOnTouch(vec, vec + len);
60 #endif
61 }
62
63 static MOZ_ALWAYS_INLINE void Debug_SetValueRangeToCrashOnTouch(
64 GCPtr<Value>* vec, size_t len) {
65 #ifdef DEBUG
66 Debug_SetValueRangeToCrashOnTouch((Value*)vec, len);
67 #endif
68 }
69
70 static MOZ_ALWAYS_INLINE void Debug_SetSlotRangeToCrashOnTouch(HeapSlot* vec,
71 uint32_t len) {
72 #ifdef DEBUG
73 Debug_SetValueRangeToCrashOnTouch((Value*)vec, len);
74 #endif
75 }
76
77 static MOZ_ALWAYS_INLINE void Debug_SetSlotRangeToCrashOnTouch(HeapSlot* begin,
78 HeapSlot* end) {
79 #ifdef DEBUG
80 Debug_SetValueRangeToCrashOnTouch((Value*)begin, end - begin);
81 #endif
82 }
83
84 class ArrayObject;
85
86 /**
87 * 10.4.2.4 ArraySetLength ( A, Desc )
88 *
89 * ES2025 draft rev ac21460fedf4b926520b06c9820bdbebad596a8b
90 *
91 * |id| must be "length", |desc| is the new non-accessor descriptor, and
92 * |result| receives an error code if the change is invalid.
93 */
94 extern bool ArraySetLength(JSContext* cx, Handle<ArrayObject*> obj, HandleId id,
95 Handle<PropertyDescriptor> desc,
96 ObjectOpResult& result);
97
98 /*
99 * [SMDOC] NativeObject Elements layout
100 *
101 * Elements header used for native objects. The elements component of such
102 * objects offers an efficient representation for all or some of the indexed
103 * properties of the object, using a flat array of Values rather than a shape
104 * hierarchy stored in the object's slots. This structure is immediately
105 * followed by an array of elements, with the elements member in an object
106 * pointing to the beginning of that array (the end of this structure). See
107 * below for usage of this structure.
108 *
109 * The sets of properties represented by an object's elements and slots
110 * are disjoint. The elements contain only indexed properties, while the slots
111 * can contain both named and indexed properties; any indexes in the slots are
112 * distinct from those in the elements. If isIndexed() is false for an object,
113 * all indexed properties (if any) are stored in the dense elements.
114 *
115 * Indexes will be stored in the object's slots instead of its elements in
116 * the following case:
117 * - there are more than MIN_SPARSE_INDEX slots total and the load factor
118 * (COUNT / capacity) is less than 0.25
119 * - a property is defined that has non-default property attributes.
120 *
121 * We track these pieces of metadata for dense elements:
122 * - The length property as a uint32_t, accessible for array objects with
123 * ArrayObject::{length,setLength}(). This is unused for non-arrays.
124 * - The number of element slots (capacity), gettable with
125 * getDenseCapacity().
126 * - The array's initialized length, accessible with
127 * getDenseInitializedLength().
128 *
129 * Holes in the array are represented by MagicValue(JS_ELEMENTS_HOLE) values.
130 * These indicate indexes which are not dense properties of the array. The
131 * property may, however, be held by the object's properties.
132 *
133 * The capacity and length of an object's elements are almost entirely
134 * unrelated! In general the length may be greater than, less than, or equal
135 * to the capacity. The first case occurs with |new Array(100)|. The length
136 * is 100, but the capacity remains 0 (indices below length and above capacity
137 * must be treated as holes) until elements between capacity and length are
138 * set. The other two cases are common, depending upon the number of elements
139 * in an array and the underlying allocator used for element storage.
140 *
141 * The only case in which the capacity and length of an object's elements are
142 * related is when the object is an array with non-writable length. In this
143 * case the capacity is always less than or equal to the length. This permits
144 * JIT code to optimize away the check for non-writable length when assigning
145 * to possibly out-of-range elements: such code already has to check for
146 * |index < capacity|, and fallback code checks for non-writable length.
147 *
148 * The initialized length of an object specifies the number of elements that
149 * have been initialized. All elements above the initialized length are
150 * holes in the object, and the memory for all elements between the initialized
151 * length and capacity is left uninitialized. The initialized length is some
152 * value less than or equal to both the object's length and the object's
153 * capacity.
154 *
155 * There is flexibility in exactly the value the initialized length must hold,
156 * e.g. if an array has length 5, capacity 10, completely empty, it is valid
157 * for the initialized length to be any value between zero and 5, as long as
158 * the in memory values below the initialized length have been initialized with
159 * a hole value. However, in such cases we want to keep the initialized length
160 * as small as possible: if the object is known to have no hole values below
161 * its initialized length, then it is "packed" and can be accessed much faster
162 * by JIT code.
163 *
164 * Elements do not track property creation order, so enumerating the elements
165 * of an object does not necessarily visit indexes in the order they were
166 * created.
167 *
168 *
169 * [SMDOC] NativeObject shifted elements optimization
170 *
171 * Shifted elements
172 * ----------------
173 * It's pretty common to use an array as a queue, like this:
174 *
175 * while (arr.length > 0)
176 * foo(arr.shift());
177 *
178 * To ensure we don't get quadratic behavior on this, elements can be 'shifted'
179 * in memory. tryShiftDenseElements does this by incrementing elements_ to point
180 * to the next element and moving the ObjectElements header in memory (so it's
181 * stored where the shifted Value used to be).
182 *
183 * Shifted elements can be moved when we grow the array, when the array is
184 * made non-extensible (for simplicity, shifted elements are not supported on
185 * objects that are non-extensible, have copy-on-write elements, or on arrays
186 * with non-writable length).
187 */
188 class ObjectElements {
189 public:
190 enum Flags : uint16_t {
191 // Elements are stored inline in the object allocation.
192 // An object allocated with the FIXED flag set can have the flag unset later
193 // if `growElements()` is called to increase the capacity beyond what was
194 // initially allocated. Once the flag is unset, it will remain so for the
195 // rest of the lifetime of the object.
196 FIXED = 0x1,
197
198 // Present only if these elements correspond to an array with
199 // non-writable length; never present for non-arrays.
200 NONWRITABLE_ARRAY_LENGTH = 0x2,
201
202 // For TypedArrays only: this TypedArray's storage is mapping shared
203 // memory. This is a static property of the TypedArray, set when it
204 // is created and never changed.
205 SHARED_MEMORY = 0x8,
206
207 // These elements are not extensible. If this flag is set, the object's
208 // Shape must also have the NotExtensible flag. This exists on
209 // ObjectElements in addition to Shape to simplify JIT code.
210 NOT_EXTENSIBLE = 0x10,
211
212 // These elements are set to integrity level "sealed". If this flag is
213 // set, the NOT_EXTENSIBLE flag must be set as well.
214 SEALED = 0x20,
215
216 // These elements are set to integrity level "frozen". If this flag is
217 // set, the SEALED flag must be set as well.
218 //
219 // This flag must only be set if the Shape has the FrozenElements flag.
220 // The Shape flag ensures a shape guard can be used to guard against frozen
221 // elements. The ObjectElements flag is convenient for JIT code and
222 // ObjectElements assertions.
223 FROZEN = 0x40,
224
225 // If this flag is not set, the elements are guaranteed to contain no hole
226 // values (the JS_ELEMENTS_HOLE MagicValue) in [0, initializedLength).
227 NON_PACKED = 0x80,
228
229 // If this flag is not set, there's definitely no for-in iterator that
230 // covers these dense elements so elements can be deleted without calling
231 // SuppressDeletedProperty. This is used by fast paths for various Array
232 // builtins. See also NativeObject::denseElementsMaybeInIteration.
233 MAYBE_IN_ITERATION = 0x100,
234 };
235
236 // The flags word stores both the flags and the number of shifted elements.
237 // Allow shifting 2047 elements before actually moving the elements.
238 static const size_t NumShiftedElementsBits = 11;
239 static const size_t MaxShiftedElements = (1 << NumShiftedElementsBits) - 1;
240 static const size_t NumShiftedElementsShift = 32 - NumShiftedElementsBits;
241 static const size_t FlagsMask = (1 << NumShiftedElementsShift) - 1;
242 static_assert(MaxShiftedElements == 2047,
243 "MaxShiftedElements should match the comment");
244
245 private:
246 friend class ::JSObject;
247 friend class ArrayObject;
248 friend class NativeObject;
249 friend class gc::TenuringTracer;
250
251 friend bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj,
252 IntegrityLevel level);
253
254 friend bool ArraySetLength(JSContext* cx, Handle<ArrayObject*> obj,
255 HandleId id, Handle<PropertyDescriptor> desc,
256 ObjectOpResult& result);
257
258 // The NumShiftedElementsBits high bits of this are used to store the
259 // number of shifted elements, the other bits are available for the flags.
260 // See Flags enum above.
261 uint32_t flags;
262
263 /*
264 * Number of initialized elements. This is <= the capacity, and for arrays
265 * is <= the length. Memory for elements above the initialized length is
266 * uninitialized, but values between the initialized length and the proper
267 * length are conceptually holes.
268 */
269 uint32_t initializedLength;
270
271 /* Number of allocated slots. */
272 uint32_t capacity;
273
274 /* 'length' property of array objects, unused for other objects. */
275 uint32_t length;
276
277 void setNonwritableArrayLength() {
278 // See ArrayObject::setNonWritableLength.
279 MOZ_ASSERT(capacity == initializedLength);
280 MOZ_ASSERT(numShiftedElements() == 0);
281 flags |= NONWRITABLE_ARRAY_LENGTH;
282 }
283
284 void addShiftedElements(uint32_t count) {
285 MOZ_ASSERT(count < capacity);
286 MOZ_ASSERT(count < initializedLength);
287 MOZ_ASSERT(!(
288 flags & (NONWRITABLE_ARRAY_LENGTH | NOT_EXTENSIBLE | SEALED | FROZEN)));
289 uint32_t numShifted = numShiftedElements() + count;
290 MOZ_ASSERT(numShifted <= MaxShiftedElements);
291 flags = (numShifted << NumShiftedElementsShift) | (flags & FlagsMask);
292 capacity -= count;
293 initializedLength -= count;
294 }
295 void unshiftShiftedElements(uint32_t count) {
296 MOZ_ASSERT(count > 0);
297 MOZ_ASSERT(!(
298 flags & (NONWRITABLE_ARRAY_LENGTH | NOT_EXTENSIBLE | SEALED | FROZEN)));
299 uint32_t numShifted = numShiftedElements();
300 MOZ_ASSERT(count <= numShifted);
301 numShifted -= count;
302 flags = (numShifted << NumShiftedElementsShift) | (flags & FlagsMask);
303 capacity += count;
304 initializedLength += count;
305 }
306 void clearShiftedElements() {
307 flags &= FlagsMask;
308 MOZ_ASSERT(numShiftedElements() == 0);
309 }
310
311 void markNonPacked() { flags |= NON_PACKED; }
312
313 void markMaybeInIteration() { flags |= MAYBE_IN_ITERATION; }
314
315 void setNotExtensible() {
316 MOZ_ASSERT(!isNotExtensible());
317 flags |= NOT_EXTENSIBLE;
318 }
319
320 void seal() {
321 MOZ_ASSERT(isNotExtensible());
322 MOZ_ASSERT(!isSealed());
323 MOZ_ASSERT(!isFrozen());
324 flags |= SEALED;
325 }
326 void freeze() {
327 MOZ_ASSERT(isNotExtensible());
328 MOZ_ASSERT(isSealed());
329 MOZ_ASSERT(!isFrozen());
330 flags |= FROZEN;
331 }
332
333 bool isFrozen() const { return flags & FROZEN; }
334
335 public:
336 constexpr ObjectElements(uint32_t capacity, uint32_t length)
337 : flags(0), initializedLength(0), capacity(capacity), length(length) {}
338
339 enum class SharedMemory { IsShared };
340
341 constexpr ObjectElements(uint32_t capacity, uint32_t length,
342 SharedMemory shmem)
343 : flags(SHARED_MEMORY),
344 initializedLength(0),
345 capacity(capacity),
346 length(length) {}
347
348 HeapSlot* elements() {
349 return reinterpret_cast<HeapSlot*>(uintptr_t(this) +
350 sizeof(ObjectElements));
351 }
352 const HeapSlot* elements() const {
353 return reinterpret_cast<const HeapSlot*>(uintptr_t(this) +
354 sizeof(ObjectElements));
355 }
356 static ObjectElements* fromElements(HeapSlot* elems) {
357 return reinterpret_cast<ObjectElements*>(uintptr_t(elems) -
358 sizeof(ObjectElements));
359 }
360
361 bool isSharedMemory() const { return flags & SHARED_MEMORY; }
362
363 static int offsetOfFlags() {
364 return int(offsetof(ObjectElements, flags)) - int(sizeof(ObjectElements));
365 }
366 static int offsetOfInitializedLength() {
367 return int(offsetof(ObjectElements, initializedLength)) -
368 int(sizeof(ObjectElements));
369 }
370 static int offsetOfCapacity() {
371 return int(offsetof(ObjectElements, capacity)) -
372 int(sizeof(ObjectElements));
373 }
374 static int offsetOfLength() {
375 return int(offsetof(ObjectElements, length)) - int(sizeof(ObjectElements));
376 }
377
378 static void PrepareForPreventExtensions(JSContext* cx, NativeObject* obj);
379 static void PreventExtensions(NativeObject* obj);
380 [[nodiscard]] static bool FreezeOrSeal(JSContext* cx,
381 Handle<NativeObject*> obj,
382 IntegrityLevel level);
383
384 bool isSealed() const { return flags & SEALED; }
385
386 bool isPacked() const { return !(flags & NON_PACKED); }
387
388 JS::PropertyAttributes elementAttributes() const {
389 if (isFrozen()) {
390 return {JS::PropertyAttribute::Enumerable};
391 }
392 if (isSealed()) {
393 return {JS::PropertyAttribute::Enumerable,
394 JS::PropertyAttribute::Writable};
395 }
396 return {JS::PropertyAttribute::Configurable,
397 JS::PropertyAttribute::Enumerable, JS::PropertyAttribute::Writable};
398 }
399
400 uint32_t numShiftedElements() const {
401 uint32_t numShifted = flags >> NumShiftedElementsShift;
402 MOZ_ASSERT_IF(numShifted > 0,
403 !(flags & (NONWRITABLE_ARRAY_LENGTH | NOT_EXTENSIBLE |
404 SEALED | FROZEN)));
405 return numShifted;
406 }
407
408 uint32_t numAllocatedElements() const {
409 return VALUES_PER_HEADER + capacity + numShiftedElements();
410 }
411
412 bool hasNonwritableArrayLength() const {
413 return flags & NONWRITABLE_ARRAY_LENGTH;
414 }
415
416 bool maybeInIteration() { return flags & MAYBE_IN_ITERATION; }
417
418 bool isNotExtensible() { return flags & NOT_EXTENSIBLE; }
419
420 // This is enough slots to store an object of this class. See the static
421 // assertion below.
422 static const size_t VALUES_PER_HEADER = 2;
423
424 #if defined(DEBUG) || defined(JS_JITSPEW)
425 void dumpStringContent(js::GenericPrinter& out) const;
426 #endif
427 };
428
429 static_assert(ObjectElements::VALUES_PER_HEADER * sizeof(HeapSlot) ==
430 sizeof(ObjectElements),
431 "ObjectElements doesn't fit in the given number of slots");
432
433 /*
434 * Slots header used for native objects. The header stores the capacity and the
435 * slot data follows in memory.
436 */
437 class alignas(HeapSlot) ObjectSlots {
438 uint32_t capacity_;
439 uint32_t dictionarySlotSpan_;
440 uint64_t maybeUniqueId_;
441
442 public:
443 // Special values for maybeUniqueId_ to indicate no unique ID is present.
444 static constexpr uint64_t NoUniqueIdInDynamicSlots = 0;
445 static constexpr uint64_t NoUniqueIdInSharedEmptySlots = 1;
446 static constexpr uint64_t LastNoUniqueIdValue = NoUniqueIdInSharedEmptySlots;
447
448 static constexpr size_t VALUES_PER_HEADER = 2;
449
450 static inline size_t allocCount(size_t slotCount) {
451 static_assert(sizeof(ObjectSlots) ==
452 ObjectSlots::VALUES_PER_HEADER * sizeof(HeapSlot));
453 #ifdef MOZ_VALGRIND
454 if (slotCount == 0) {
455 // Add an extra unused slot so that NativeObject::slots_ always points
456 // into the allocation otherwise valgrind thinks this is a leak.
457 slotCount = 1;
458 }
459 #endif
460 return slotCount + VALUES_PER_HEADER;
461 }
462
463 static inline size_t allocSize(size_t slotCount) {
464 return allocCount(slotCount) * sizeof(HeapSlot);
465 }
466
467 static ObjectSlots* fromSlots(HeapSlot* slots) {
468 MOZ_ASSERT(slots);
469 return reinterpret_cast<ObjectSlots*>(uintptr_t(slots) -
470 sizeof(ObjectSlots));
471 }
472
473 static constexpr size_t offsetOfCapacity() {
474 return offsetof(ObjectSlots, capacity_);
475 }
476 static constexpr size_t offsetOfDictionarySlotSpan() {
477 return offsetof(ObjectSlots, dictionarySlotSpan_);
478 }
479 static constexpr size_t offsetOfMaybeUniqueId() {
480 return offsetof(ObjectSlots, maybeUniqueId_);
481 }
482 static constexpr size_t offsetOfSlots() { return sizeof(ObjectSlots); }
483
484 constexpr ObjectSlots(uint32_t capacity, uint32_t dictionarySlotSpan,
485 uint64_t maybeUniqueId);
486
487 constexpr uint32_t capacity() const { return capacity_; }
488
489 constexpr uint32_t dictionarySlotSpan() const { return dictionarySlotSpan_; }
490
491 bool isSharedEmptySlots() const {
492 return maybeUniqueId_ == NoUniqueIdInSharedEmptySlots;
493 }
494
495 constexpr bool hasUniqueId() const {
496 return maybeUniqueId_ > LastNoUniqueIdValue;
497 }
498 uint64_t uniqueId() const {
499 MOZ_ASSERT(hasUniqueId());
500 return maybeUniqueId_;
501 }
502 uintptr_t maybeUniqueId() const { return hasUniqueId() ? maybeUniqueId_ : 0; }
503 void setUniqueId(uint64_t uid) {
504 MOZ_ASSERT(uid > LastNoUniqueIdValue);
505 MOZ_ASSERT(!isSharedEmptySlots());
506 maybeUniqueId_ = uid;
507 }
508
509 void setDictionarySlotSpan(uint32_t span) { dictionarySlotSpan_ = span; }
510
511 HeapSlot* slots() const {
512 return reinterpret_cast<HeapSlot*>(uintptr_t(this) + sizeof(ObjectSlots));
513 }
514 };
515
516 /*
517 * Shared singletons for objects with no elements.
518 * emptyObjectElementsShared is used only for TypedArrays, when the TA
519 * maps shared memory.
520 */
521 extern HeapSlot* const emptyObjectElements;
522 extern HeapSlot* const emptyObjectElementsShared;
523
524 /*
525 * Shared singletons for objects with no dynamic slots.
526 */
527 extern HeapSlot* const emptyObjectSlots;
528 extern HeapSlot* const emptyObjectSlotsForDictionaryObject[];
529
530 class AutoCheckShapeConsistency;
531 class GCMarker;
532
533 // Operations which change an object's dense elements can either succeed, fail,
534 // or be unable to complete. The latter is used when the object's elements must
535 // become sparse instead. The enum below is used for such operations.
536 enum class DenseElementResult { Failure, Success, Incomplete };
537
538 // Stores a slot offset in bytes relative to either the NativeObject* address
539 // (if isFixedSlot) or to NativeObject::slots_ (if !isFixedSlot).
540 class TaggedSlotOffset {
541 uint32_t bits_ = 0;
542
543 public:
544 static constexpr size_t OffsetShift = 1;
545 static constexpr size_t IsFixedSlotFlag = 0b1;
546
547 static constexpr size_t MaxOffset = SHAPE_MAXIMUM_SLOT * sizeof(Value);
548 static_assert((uint64_t(MaxOffset) << OffsetShift) <= UINT32_MAX,
549 "maximum slot offset must fit in TaggedSlotOffset");
550
551 constexpr TaggedSlotOffset() = default;
552
553 TaggedSlotOffset(uint32_t offset, bool isFixedSlot)
554 : bits_((offset << OffsetShift) | isFixedSlot) {
555 MOZ_ASSERT(offset <= MaxOffset);
556 }
557
558 uint32_t offset() const { return bits_ >> OffsetShift; }
559 bool isFixedSlot() const { return bits_ & IsFixedSlotFlag; }
560
561 bool operator==(const TaggedSlotOffset& other) const {
562 return bits_ == other.bits_;
563 }
564 bool operator!=(const TaggedSlotOffset& other) const {
565 return !(*this == other);
566 }
567 };
568
569 enum class CanReuseShape {
570 // The Shape can be reused. This implies CanReusePropMap.
571 CanReuseShape,
572
573 // Only the PropMap can be reused.
574 CanReusePropMap,
575
576 // Neither the PropMap nor Shape can be reused.
577 NoReuse,
578 };
579
580 /*
581 * [SMDOC] NativeObject layout
582 *
583 * NativeObject specifies the internal implementation of a native object.
584 *
585 * Native objects use ShapedObject::shape to record property information. Two
586 * native objects with the same shape are guaranteed to have the same number of
587 * fixed slots.
588 *
589 * Native objects extend the base implementation of an object with storage for
590 * the object's named properties and indexed elements.
591 *
592 * These are stored separately from one another. Objects are followed by a
593 * variable-sized array of values for inline storage, which may be used by
594 * either properties of native objects (fixed slots), by elements (fixed
595 * elements), or by other data for certain kinds of objects, such as
596 * ArrayBufferObjects and TypedArrayObjects.
597 *
598 * Named property storage can be split between fixed slots and a dynamically
599 * allocated array (the slots member). For an object with N fixed slots, shapes
600 * with slots [0..N-1] are stored in the fixed slots, and the remainder are
601 * stored in the dynamic array. If all properties fit in the fixed slots, the
602 * 'slots_' member is nullptr.
603 *
604 * Elements are indexed via the 'elements_' member. This member can point to
605 * either the shared emptyObjectElements and emptyObjectElementsShared
606 * singletons, into the inline value array (the address of the third value, to
607 * leave room for a ObjectElements header;in this case numFixedSlots() is zero)
608 * or to a dynamically allocated array.
609 *
610 * Slots and elements may both be non-empty. The slots may be either names or
611 * indexes; no indexed property will be in both the slots and elements.
612 */
613 class NativeObject : public JSObject {
614 protected:
615 /* Slots for object properties. */
616 js::HeapSlot* slots_;
617
618 /* Slots for object dense elements. */
619 js::HeapSlot* elements_;
620
621 friend class ::JSObject;
622
623 private:
624 static void staticAsserts() {
625 static_assert(sizeof(NativeObject) == sizeof(JSObject_Slots0),
626 "native object size must match GC thing size");
627 static_assert(sizeof(NativeObject) == sizeof(JS::shadow::Object),
628 "shadow interface must match actual implementation");
629 static_assert(sizeof(NativeObject) % sizeof(Value) == 0,
630 "fixed slots after an object must be aligned");
631
632 static_assert(offsetOfShape() == offsetof(JS::shadow::Object, shape),
633 "shadow type must match actual type");
634 static_assert(
635 offsetof(NativeObject, slots_) == offsetof(JS::shadow::Object, slots),
636 "shadow slots must match actual slots");
637 static_assert(
638 offsetof(NativeObject, elements_) == offsetof(JS::shadow::Object, _1),
639 "shadow placeholder must match actual elements");
640
641 static_assert(MAX_FIXED_SLOTS <= Shape::FIXED_SLOTS_MAX,
642 "verify numFixedSlots() bitfield is big enough");
643 static_assert(sizeof(NativeObject) + MAX_FIXED_SLOTS * sizeof(Value) ==
644 JSObject::MAX_BYTE_SIZE,
645 "inconsistent maximum object size");
646
647 // Sanity check NativeObject size is what we expect.
648 #ifdef JS_64BIT
649 static_assert(sizeof(NativeObject) == 3 * sizeof(void*));
650 #else
651 static_assert(sizeof(NativeObject) == 4 * sizeof(void*));
652 #endif
653 }
654
655 public:
656 NativeShape* shape() const { return &JSObject::shape()->asNative(); }
657 SharedShape* sharedShape() const { return &shape()->asShared(); }
658 DictionaryShape* dictionaryShape() const { return &shape()->asDictionary(); }
659
660 PropertyInfoWithKey getLastProperty() const {
661 return shape()->lastProperty();
662 }
663
664 HeapSlotArray getDenseElements() const { return HeapSlotArray(elements_); }
665
666 const Value& getDenseElement(uint32_t idx) const {
667 MOZ_ASSERT(idx < getDenseInitializedLength());
668 return elements_[idx];
669 }
670 bool containsDenseElement(uint32_t idx) const {
671 return idx < getDenseInitializedLength() &&
672 !elements_[idx].isMagic(JS_ELEMENTS_HOLE);
673 }
674 uint32_t getDenseInitializedLength() const {
675 return getElementsHeader()->initializedLength;
676 }
677 uint32_t getDenseCapacity() const { return getElementsHeader()->capacity; }
678
679 bool isSharedMemory() const { return getElementsHeader()->isSharedMemory(); }
680
681 // Update the object's shape and allocate slots if needed to match the shape's
682 // slot span.
683 MOZ_ALWAYS_INLINE bool setShapeAndAddNewSlots(JSContext* cx,
684 SharedShape* newShape,
685 uint32_t oldSpan,
686 uint32_t newSpan);
687
688 // Methods optimized for adding/removing a single slot. Must only be used for
689 // non-dictionary objects.
690 MOZ_ALWAYS_INLINE bool setShapeAndAddNewSlot(JSContext* cx,
691 SharedShape* newShape,
692 uint32_t slot);
693 void setShapeAndRemoveLastSlot(JSContext* cx, SharedShape* newShape,
694 uint32_t slot);
695
696 MOZ_ALWAYS_INLINE CanReuseShape
697 canReuseShapeForNewProperties(NativeShape* newShape) const {
698 NativeShape* oldShape = shape();
699 MOZ_ASSERT(oldShape->propMapLength() == 0,
700 "object must have no properties");
701 MOZ_ASSERT(newShape->propMapLength() > 0,
702 "new shape must have at least one property");
703 if (oldShape->isDictionary() || newShape->isDictionary()) {
704 return CanReuseShape::NoReuse;
705 }
706 // We only handle the common case where the old shape has no object flags
707 // (expected because it's an empty object) and the new shape has just the
708 // HasEnumerable flag that we can copy safely.
709 if (!oldShape->objectFlags().isEmpty()) {
710 return CanReuseShape::NoReuse;
711 }
712 MOZ_ASSERT(newShape->hasObjectFlag(ObjectFlag::HasEnumerable));
713 if (newShape->objectFlags() != ObjectFlags({ObjectFlag::HasEnumerable})) {
714 return CanReuseShape::NoReuse;
715 }
716 // If the number of fixed slots or the BaseShape is different, we can't
717 // reuse the Shape but we can still reuse the PropMap.
718 if (oldShape->numFixedSlots() != newShape->numFixedSlots() ||
719 oldShape->base() != newShape->base()) {
720 return CanReuseShape::CanReusePropMap;
721 }
722 MOZ_ASSERT(oldShape->getObjectClass() == newShape->getObjectClass());
723 MOZ_ASSERT(oldShape->proto() == newShape->proto());
724 MOZ_ASSERT(oldShape->realm() == newShape->realm());
725 return CanReuseShape::CanReuseShape;
726 }
727
728 // Newly-created TypedArrays that map a SharedArrayBuffer are
729 // marked as shared by giving them an ObjectElements that has the
730 // ObjectElements::SHARED_MEMORY flag set.
731 void setIsSharedMemory() {
732 MOZ_ASSERT(elements_ == emptyObjectElements);
733 elements_ = emptyObjectElementsShared;
734 }
735
736 static inline NativeObject* create(JSContext* cx, gc::AllocKind kind,
737 gc::Heap heap, Handle<SharedShape*> shape,
738 gc::AllocSite* site = nullptr);
739
740 template <typename T>
741 static inline T* create(JSContext* cx, gc::AllocKind kind, gc::Heap heap,
742 Handle<SharedShape*> shape,
743 gc::AllocSite* site = nullptr) {
744 NativeObject* nobj = create(cx, kind, heap, shape, site);
745 return nobj ? &nobj->as<T>() : nullptr;
746 }
747
748 #ifdef DEBUG
749 static void enableShapeConsistencyChecks();
750 #endif
751
752 protected:
753 #ifdef DEBUG
754 friend class js::AutoCheckShapeConsistency;
755 void checkShapeConsistency();
756 #else
757 void checkShapeConsistency() {}
758 #endif
759
760 void maybeFreeDictionaryPropSlots(JSContext* cx, DictionaryPropMap* map,
761 uint32_t mapLength);
762
763 [[nodiscard]] static bool toDictionaryMode(JSContext* cx,
764 Handle<NativeObject*> obj);
765
766 private:
767 inline void setEmptyDynamicSlots(uint32_t dictonarySlotSpan);
768
769 inline void setDictionaryModeSlotSpan(uint32_t span);
770
771 friend class gc::TenuringTracer;
772
773 // Given a slot range from |start| to |end| exclusive, call |fun| with
774 // pointers to the corresponding fixed slot and/or dynamic slot ranges.
775 template <typename Fun>
776 void forEachSlotRangeUnchecked(uint32_t start, uint32_t end, const Fun& fun) {
777 MOZ_ASSERT(end >= start);
778 uint32_t nfixed = numFixedSlots();
779 if (start < nfixed) {
780 HeapSlot* fixedStart = &fixedSlots()[start];
781 HeapSlot* fixedEnd = &fixedSlots()[std::min(nfixed, end)];
782 fun(fixedStart, fixedEnd);
783 start = nfixed;
784 }
785 if (end > nfixed) {
786 HeapSlot* dynStart = &slots_[start - nfixed];
787 HeapSlot* dynEnd = &slots_[end - nfixed];
788 fun(dynStart, dynEnd);
789 }
790 }
791
792 template <typename Fun>
793 void forEachSlotRange(uint32_t start, uint32_t end, const Fun& fun) {
794 MOZ_ASSERT(slotInRange(end, SENTINEL_ALLOWED));
795 forEachSlotRangeUnchecked(start, end, fun);
796 }
797
798 protected:
799 friend class DictionaryPropMap;
800 friend class GCMarker;
801 friend class Shape;
802
803 void invalidateSlotRange(uint32_t start, uint32_t end) {
804 #ifdef DEBUG
805 forEachSlotRange(start, end, [](HeapSlot* slotsStart, HeapSlot* slotsEnd) {
806 Debug_SetSlotRangeToCrashOnTouch(slotsStart, slotsEnd);
807 });
808 #endif /* DEBUG */
809 }
810
811 void initFixedSlots(uint32_t numSlots) {
812 MOZ_ASSERT(numSlots == numUsedFixedSlots());
813 HeapSlot* slots = fixedSlots();
814 for (uint32_t i = 0; i < numSlots; i++) {
815 slots[i].initAsUndefined();
816 }
817 }
818 void initDynamicSlots(uint32_t numSlots) {
819 MOZ_ASSERT(numSlots == sharedShape()->slotSpan() - numFixedSlots());
820 HeapSlot* slots = slots_;
821 for (uint32_t i = 0; i < numSlots; i++) {
822 slots[i].initAsUndefined();
823 }
824 }
825 void initSlots(uint32_t nfixed, uint32_t slotSpan) {
826 initFixedSlots(std::min(nfixed, slotSpan));
827 if (slotSpan > nfixed) {
828 initDynamicSlots(slotSpan - nfixed);
829 }
830 }
831
832 #ifdef DEBUG
833 enum SentinelAllowed { SENTINEL_NOT_ALLOWED, SENTINEL_ALLOWED };
834
835 /*
836 * Check that slot is in range for the object's allocated slots.
837 * If sentinelAllowed then slot may equal the slot capacity.
838 */
839 bool slotInRange(uint32_t slot,
840 SentinelAllowed sentinel = SENTINEL_NOT_ALLOWED) const;
841
842 /*
843 * Check whether a slot is a fixed slot.
844 */
845 bool slotIsFixed(uint32_t slot) const;
846
847 /*
848 * Check whether the supplied number of fixed slots is correct.
849 */
850 bool isNumFixedSlots(uint32_t nfixed) const;
851 #endif
852
853 /*
854 * Minimum size for dynamically allocated slots in normal Objects.
855 * ArrayObjects don't use this limit and can have a lower slot capacity,
856 * since they normally don't have a lot of slots.
857 */
858 static const uint32_t SLOT_CAPACITY_MIN = 6;
859
860 /*
861 * Minimum size for dynamically allocated elements in normal Objects.
862 */
863 static const uint32_t ELEMENT_CAPACITY_MIN = 6;
864
865 HeapSlot* fixedSlots() const {
866 return reinterpret_cast<HeapSlot*>(uintptr_t(this) + sizeof(NativeObject));
867 }
868
869 public:
870 inline void initEmptyDynamicSlots();
871
872 [[nodiscard]] static bool generateNewDictionaryShape(
873 JSContext* cx, Handle<NativeObject*> obj);
874
875 // The maximum number of slots in an object.
876 // |MAX_SLOTS_COUNT * sizeof(JS::Value)| shouldn't overflow
877 // int32_t (see slotsSizeMustNotOverflow).
878 static const uint32_t MAX_SLOTS_COUNT = (1 << 28) - 1;
879
880 static void slotsSizeMustNotOverflow() {
881 static_assert(
882 NativeObject::MAX_SLOTS_COUNT <= INT32_MAX / sizeof(JS::Value),
883 "every caller of this method requires that a slot "
884 "number (or slot count) count multiplied by "
885 "sizeof(Value) can't overflow uint32_t (and sometimes "
886 "int32_t, too)");
887 }
888
889 uint32_t numFixedSlots() const {
890 return reinterpret_cast<const JS::shadow::Object*>(this)->numFixedSlots();
891 }
892
893 // Get the number of fixed slots when the shape pointer may have been
894 // forwarded by a moving GC. You need to use this rather that
895 // numFixedSlots() in a trace hook if you access an object that is not the
896 // object being traced, since it may have a stale shape pointer.
897 inline uint32_t numFixedSlotsMaybeForwarded() const;
898
899 uint32_t numUsedFixedSlots() const {
900 uint32_t nslots = sharedShape()->slotSpan();
901 return std::min(nslots, numFixedSlots());
902 }
903
904 uint32_t slotSpan() const {
905 if (inDictionaryMode()) {
906 return dictionaryModeSlotSpan();
907 }
908 MOZ_ASSERT(getSlotsHeader()->dictionarySlotSpan() == 0);
909 return sharedShape()->slotSpan();
910 }
911
912 uint32_t dictionaryModeSlotSpan() const {
913 MOZ_ASSERT(inDictionaryMode());
914 return getSlotsHeader()->dictionarySlotSpan();
915 }
916
917 /* Whether a slot is at a fixed offset from this object. */
918 bool isFixedSlot(size_t slot) { return slot < numFixedSlots(); }
919
920 /* Index into the dynamic slots array to use for a dynamic slot. */
921 size_t dynamicSlotIndex(size_t slot) {
922 MOZ_ASSERT(slot >= numFixedSlots());
923 return slot - numFixedSlots();
924 }
925
926 // Native objects are never proxies. Call isExtensible instead.
927 bool nonProxyIsExtensible() const = delete;
928
929 bool isExtensible() const { return !hasFlag(ObjectFlag::NotExtensible); }
930
931 /*
932 * Whether there may be indexed properties on this object, excluding any in
933 * the object's elements.
934 */
935 bool isIndexed() const { return hasFlag(ObjectFlag::Indexed); }
936
937 bool hasInterestingSymbol() const {
938 return hasFlag(ObjectFlag::HasInterestingSymbol);
939 }
940
941 bool hasEnumerableProperty() const {
942 return hasFlag(ObjectFlag::HasEnumerable);
943 }
944
945 static bool setHadGetterSetterChange(JSContext* cx,
946 Handle<NativeObject*> obj) {
947 return setFlag(cx, obj, ObjectFlag::HadGetterSetterChange);
948 }
949 bool hadGetterSetterChange() const {
950 return hasFlag(ObjectFlag::HadGetterSetterChange);
951 }
952
953 bool allocateInitialSlots(JSContext* cx, uint32_t capacity);
954
955 /*
956 * Grow or shrink slots immediately before changing the slot span.
957 * The number of allocated slots is not stored explicitly, and changes to
958 * the slots must track changes in the slot span.
959 */
960 bool growSlots(JSContext* cx, uint32_t oldCapacity, uint32_t newCapacity);
961 bool growSlotsForNewSlot(JSContext* cx, uint32_t numFixed, uint32_t slot);
962 void shrinkSlots(JSContext* cx, uint32_t oldCapacity, uint32_t newCapacity);
963
964 bool allocateSlots(Nursery& nursery, uint32_t newCapacity);
965
966 /*
967 * This method is static because it's called from JIT code. On OOM, returns
968 * false without leaving a pending exception on the context.
969 */
970 static bool growSlotsPure(JSContext* cx, NativeObject* obj,
971 uint32_t newCapacity);
972
973 /*
974 * Like growSlotsPure but for dense elements. This will return
975 * false if we failed to allocate a dense element for some reason (OOM, too
976 * many dense elements, non-writable array length, etc).
977 */
978 static bool addDenseElementPure(JSContext* cx, NativeObject* obj);
979
980 /*
981 * Indicates whether this object has an ObjectSlots allocation attached. The
982 * capacity of this can be zero if it is only used to hold a unique ID.
983 */
984 bool hasDynamicSlots() const {
985 return !getSlotsHeader()->isSharedEmptySlots();
986 }
987
988 /* Compute the number of dynamic slots required for this object. */
989 MOZ_ALWAYS_INLINE uint32_t calculateDynamicSlots() const;
990
991 MOZ_ALWAYS_INLINE uint32_t numDynamicSlots() const;
992
993 #ifdef DEBUG
994 uint32_t outOfLineNumDynamicSlots() const;
995 #endif
996
997 bool empty() const { return shape()->propMapLength() == 0; }
998
999 mozilla::Maybe<PropertyInfo> lookup(JSContext* cx, jsid id);
1000 mozilla::Maybe<PropertyInfo> lookup(JSContext* cx, PropertyName* name) {
1001 return lookup(cx, NameToId(name));
1002 }
1003
1004 bool contains(JSContext* cx, jsid id) { return lookup(cx, id).isSome(); }
1005 bool contains(JSContext* cx, PropertyName* name) {
1006 return lookup(cx, name).isSome();
1007 }
1008 bool contains(JSContext* cx, jsid id, PropertyInfo prop) {
1009 mozilla::Maybe<PropertyInfo> found = lookup(cx, id);
1010 return found.isSome() && *found == prop;
1011 }
1012
1013 /* Contextless; can be called from other pure code. */
1014 mozilla::Maybe<PropertyInfo> lookupPure(jsid id);
1015 mozilla::Maybe<PropertyInfo> lookupPure(PropertyName* name) {
1016 return lookupPure(NameToId(name));
1017 }
1018
1019 bool containsPure(jsid id) { return lookupPure(id).isSome(); }
1020 bool containsPure(PropertyName* name) { return containsPure(NameToId(name)); }
1021 bool containsPure(jsid id, PropertyInfo prop) {
1022 mozilla::Maybe<PropertyInfo> found = lookupPure(id);
1023 return found.isSome() && *found == prop;
1024 }
1025
1026 private:
1027 /*
1028 * Allocate and free an object slot.
1029 *
1030 * FIXME: bug 593129 -- slot allocation should be done by object methods
1031 * after calling object-parameter-free shape methods, avoiding coupling
1032 * logic across the object vs. shape module wall.
1033 */
1034 static bool allocDictionarySlot(JSContext* cx, Handle<NativeObject*> obj,
1035 uint32_t* slotp);
1036
1037 void freeDictionarySlot(uint32_t slot);
1038
1039 static MOZ_ALWAYS_INLINE bool maybeConvertToDictionaryForAdd(
1040 JSContext* cx, Handle<NativeObject*> obj);
1041
1042 public:
1043 // Add a new property. Must only be used when the |id| is not already present
1044 // in the object's shape. Checks for non-extensibility must be done by the
1045 // callers.
1046 static bool addProperty(JSContext* cx, Handle<NativeObject*> obj, HandleId id,
1047 PropertyFlags flags, uint32_t* slotOut);
1048
1049 static bool addProperty(JSContext* cx, Handle<NativeObject*> obj,
1050 Handle<PropertyName*> name, PropertyFlags flags,
1051 uint32_t* slotOut) {
1052 RootedId id(cx, NameToId(name));
1053 return addProperty(cx, obj, id, flags, slotOut);
1054 }
1055
1056 static bool addPropertyInReservedSlot(JSContext* cx,
1057 Handle<NativeObject*> obj, HandleId id,
1058 uint32_t slot, PropertyFlags flags);
1059 static bool addPropertyInReservedSlot(JSContext* cx,
1060 Handle<NativeObject*> obj,
1061 Handle<PropertyName*> name,
1062 uint32_t slot, PropertyFlags flags) {
1063 RootedId id(cx, NameToId(name));
1064 return addPropertyInReservedSlot(cx, obj, id, slot, flags);
1065 }
1066
1067 static bool addCustomDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1068 HandleId id, PropertyFlags flags);
1069
1070 // Change a property with key |id| in this object. The object must already
1071 // have a property (stored in the shape tree) with this |id|.
1072 static bool changeProperty(JSContext* cx, Handle<NativeObject*> obj,
1073 HandleId id, PropertyFlags flags,
1074 uint32_t* slotOut);
1075
1076 static bool changeCustomDataPropAttributes(JSContext* cx,
1077 Handle<NativeObject*> obj,
1078 HandleId id, PropertyFlags flags);
1079
1080 // Remove the property named by id from this object.
1081 static bool removeProperty(JSContext* cx, Handle<NativeObject*> obj,
1082 HandleId id);
1083
1084 static bool freezeOrSealProperties(JSContext* cx, Handle<NativeObject*> obj,
1085 IntegrityLevel level);
1086
1087 protected:
1088 static bool changeNumFixedSlotsAfterSwap(JSContext* cx,
1089 Handle<NativeObject*> obj,
1090 uint32_t nfixed);
1091
1092 // For use from JSObject::swap.
1093 [[nodiscard]] bool prepareForSwap(JSContext* cx, JSObject* other,
1094 MutableHandleValueVector slotValuesOut);
1095 [[nodiscard]] static bool fixupAfterSwap(JSContext* cx,
1096 Handle<NativeObject*> obj,
1097 gc::AllocKind kind,
1098 HandleValueVector slotValues);
1099
1100 public:
1101 // Return true if this object has been converted from shared-immutable
1102 // shapes to object-owned dictionary shapes.
1103 bool inDictionaryMode() const { return shape()->isDictionary(); }
1104
1105 const Value& getSlot(uint32_t slot) const {
1106 MOZ_ASSERT(slotInRange(slot));
1107 uint32_t fixed = numFixedSlots();
1108 if (slot < fixed) {
1109 return fixedSlots()[slot];
1110 }
1111 return slots_[slot - fixed];
1112 }
1113
1114 const HeapSlot* getSlotAddressUnchecked(uint32_t slot) const {
1115 uint32_t fixed = numFixedSlots();
1116 if (slot < fixed) {
1117 return fixedSlots() + slot;
1118 }
1119 return slots_ + (slot - fixed);
1120 }
1121
1122 HeapSlot* getSlotAddressUnchecked(uint32_t slot) {
1123 uint32_t fixed = numFixedSlots();
1124 if (slot < fixed) {
1125 return fixedSlots() + slot;
1126 }
1127 return slots_ + (slot - fixed);
1128 }
1129
1130 HeapSlot* getSlotsUnchecked() { return slots_; }
1131
1132 HeapSlot* getSlotAddress(uint32_t slot) {
1133 /*
1134 * This can be used to get the address of the end of the slots for the
1135 * object, which may be necessary when fetching zero-length arrays of
1136 * slots (e.g. for callObjVarArray).
1137 */
1138 MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
1139 return getSlotAddressUnchecked(slot);
1140 }
1141
1142 const HeapSlot* getSlotAddress(uint32_t slot) const {
1143 /*
1144 * This can be used to get the address of the end of the slots for the
1145 * object, which may be necessary when fetching zero-length arrays of
1146 * slots (e.g. for callObjVarArray).
1147 */
1148 MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
1149 return getSlotAddressUnchecked(slot);
1150 }
1151
1152 MOZ_ALWAYS_INLINE HeapSlot& getSlotRef(uint32_t slot) {
1153 MOZ_ASSERT(slotInRange(slot));
1154 return *getSlotAddress(slot);
1155 }
1156
1157 MOZ_ALWAYS_INLINE const HeapSlot& getSlotRef(uint32_t slot) const {
1158 MOZ_ASSERT(slotInRange(slot));
1159 return *getSlotAddress(slot);
1160 }
1161
1162 // Check requirements on values stored to this object.
1163 MOZ_ALWAYS_INLINE void checkStoredValue(const Value& v) {
1164 MOZ_ASSERT(IsObjectValueInCompartment(v, compartment()));
1165 MOZ_ASSERT(AtomIsMarked(zoneFromAnyThread(), v));
1166 MOZ_ASSERT_IF(v.isMagic() && v.whyMagic() == JS_ELEMENTS_HOLE,
1167 !denseElementsArePacked());
1168 }
1169
1170 MOZ_ALWAYS_INLINE void setSlot(uint32_t slot, const Value& value) {
1171 MOZ_ASSERT(slotInRange(slot));
1172 checkStoredValue(value);
1173 getSlotRef(slot).set(this, HeapSlot::Slot, slot, value);
1174 }
1175
1176 MOZ_ALWAYS_INLINE void initSlot(uint32_t slot, const Value& value) {
1177 MOZ_ASSERT(getSlot(slot).isUndefined());
1178 MOZ_ASSERT(slotInRange(slot));
1179 checkStoredValue(value);
1180 initSlotUnchecked(slot, value);
1181 }
1182
1183 MOZ_ALWAYS_INLINE void initSlotUnchecked(uint32_t slot, const Value& value) {
1184 getSlotAddressUnchecked(slot)->init(this, HeapSlot::Slot, slot, value);
1185 }
1186
1187 // Returns the GetterSetter for an accessor property.
1188 GetterSetter* getGetterSetter(uint32_t slot) const {
1189 return getSlot(slot).toGCThing()->as<GetterSetter>();
1190 }
1191 GetterSetter* getGetterSetter(PropertyInfo prop) const {
1192 MOZ_ASSERT(prop.isAccessorProperty());
1193 return getGetterSetter(prop.slot());
1194 }
1195
1196 // Returns the (possibly nullptr) getter or setter object. |prop| and |slot|
1197 // must be (for) an accessor property.
1198 JSObject* getGetter(uint32_t slot) const {
1199 return getGetterSetter(slot)->getter();
1200 }
1201 JSObject* getGetter(PropertyInfo prop) const {
1202 return getGetterSetter(prop)->getter();
1203 }
1204 JSObject* getSetter(PropertyInfo prop) const {
1205 return getGetterSetter(prop)->setter();
1206 }
1207
1208 // Returns true if the property has a non-nullptr getter or setter object.
1209 // |prop| can be any property.
1210 bool hasGetter(PropertyInfo prop) const {
1211 return prop.isAccessorProperty() && getGetter(prop);
1212 }
1213 bool hasSetter(PropertyInfo prop) const {
1214 return prop.isAccessorProperty() && getSetter(prop);
1215 }
1216
1217 // If the property has a non-nullptr getter/setter, return it as ObjectValue.
1218 // Else return |undefined|. |prop| must be an accessor property.
1219 Value getGetterValue(PropertyInfo prop) const {
1220 MOZ_ASSERT(prop.isAccessorProperty());
1221 if (JSObject* getterObj = getGetter(prop)) {
1222 return ObjectValue(*getterObj);
1223 }
1224 return UndefinedValue();
1225 }
1226 Value getSetterValue(PropertyInfo prop) const {
1227 MOZ_ASSERT(prop.isAccessorProperty());
1228 if (JSObject* setterObj = getSetter(prop)) {
1229 return ObjectValue(*setterObj);
1230 }
1231 return UndefinedValue();
1232 }
1233
1234 [[nodiscard]] bool setUniqueId(JSRuntime* runtime, uint64_t uid);
1235 inline bool hasUniqueId() const { return getSlotsHeader()->hasUniqueId(); }
1236 inline uint64_t uniqueId() const { return getSlotsHeader()->uniqueId(); }
1237 inline uint64_t maybeUniqueId() const {
1238 return getSlotsHeader()->maybeUniqueId();
1239 }
1240 bool setOrUpdateUniqueId(JSContext* cx, uint64_t uid);
1241
1242 // MAX_FIXED_SLOTS is the biggest number of fixed slots our GC
1243 // size classes will give an object.
1244 static constexpr uint32_t MAX_FIXED_SLOTS =
1245 JS::shadow::Object::MAX_FIXED_SLOTS;
1246
1247 private:
1248 void prepareElementRangeForOverwrite(size_t start, size_t end) {
1249 MOZ_ASSERT(end <= getDenseInitializedLength());
1250 for (size_t i = start; i < end; i++) {
1251 elements_[i].destroy();
1252 }
1253 }
1254
1255 /*
1256 * Trigger the write barrier on a range of slots that will no longer be
1257 * reachable.
1258 */
1259 void prepareSlotRangeForOverwrite(size_t start, size_t end) {
1260 for (size_t i = start; i < end; i++) {
1261 getSlotAddressUnchecked(i)->destroy();
1262 }
1263 }
1264
1265 inline void shiftDenseElementsUnchecked(uint32_t count);
1266
1267 // Like getSlotRef, but optimized for reserved slots. This relies on the fact
1268 // that the first reserved slots (up to MAX_FIXED_SLOTS) are always stored in
1269 // fixed slots. This lets the compiler optimize away the branch below when
1270 // |index| is a constant (after inlining).
1271 //
1272 // Note: objects that may be swapped have less predictable slot layouts
1273 // because they could have been swapped with an object with fewer fixed slots.
1274 // Fortunately, the only native objects that can be swapped are DOM objects
1275 // and these shouldn't end up here (asserted below).
1276 MOZ_ALWAYS_INLINE HeapSlot& getReservedSlotRef(uint32_t index) {
1277 MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
1278 MOZ_ASSERT(slotIsFixed(index) == (index < MAX_FIXED_SLOTS));
1279 MOZ_ASSERT(!ObjectMayBeSwapped(this));
1280 return index < MAX_FIXED_SLOTS ? fixedSlots()[index]
1281 : slots_[index - MAX_FIXED_SLOTS];
1282 }
1283 MOZ_ALWAYS_INLINE const HeapSlot& getReservedSlotRef(uint32_t index) const {
1284 MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
1285 MOZ_ASSERT(slotIsFixed(index) == (index < MAX_FIXED_SLOTS));
1286 MOZ_ASSERT(!ObjectMayBeSwapped(this));
1287 return index < MAX_FIXED_SLOTS ? fixedSlots()[index]
1288 : slots_[index - MAX_FIXED_SLOTS];
1289 }
1290
1291 public:
1292 MOZ_ALWAYS_INLINE const Value& getReservedSlot(uint32_t index) const {
1293 return getReservedSlotRef(index);
1294 }
1295 MOZ_ALWAYS_INLINE void initReservedSlot(uint32_t index, const Value& v) {
1296 MOZ_ASSERT(getReservedSlot(index).isUndefined());
1297 checkStoredValue(v);
1298 getReservedSlotRef(index).init(this, HeapSlot::Slot, index, v);
1299 }
1300 MOZ_ALWAYS_INLINE void setReservedSlot(uint32_t index, const Value& v) {
1301 checkStoredValue(v);
1302 getReservedSlotRef(index).set(this, HeapSlot::Slot, index, v);
1303 }
1304
1305 // For slots which are known to always be fixed, due to the way they are
1306 // allocated.
1307
1308 HeapSlot& getFixedSlotRef(uint32_t slot) {
1309 MOZ_ASSERT(slotIsFixed(slot));
1310 return fixedSlots()[slot];
1311 }
1312
1313 const Value& getFixedSlot(uint32_t slot) const {
1314 MOZ_ASSERT(slotIsFixed(slot));
1315 return fixedSlots()[slot];
1316 }
1317
1318 const Value& getDynamicSlot(uint32_t dynamicSlotIndex) const {
1319 MOZ_ASSERT(dynamicSlotIndex < outOfLineNumDynamicSlots());
1320 return slots_[dynamicSlotIndex];
1321 }
1322
1323 void setFixedSlot(uint32_t slot, const Value& value) {
1324 MOZ_ASSERT(slotIsFixed(slot));
1325 checkStoredValue(value);
1326 fixedSlots()[slot].set(this, HeapSlot::Slot, slot, value);
1327 }
1328
1329 void setDynamicSlot(uint32_t numFixed, uint32_t slot, const Value& value) {
1330 MOZ_ASSERT(numFixedSlots() == numFixed);
1331 MOZ_ASSERT(slot >= numFixed);
1332 MOZ_ASSERT(slot - numFixed < getSlotsHeader()->capacity());
1333 checkStoredValue(value);
1334 slots_[slot - numFixed].set(this, HeapSlot::Slot, slot, value);
1335 }
1336
1337 void initFixedSlot(uint32_t slot, const Value& value) {
1338 MOZ_ASSERT(slotIsFixed(slot));
1339 checkStoredValue(value);
1340 fixedSlots()[slot].init(this, HeapSlot::Slot, slot, value);
1341 }
1342
1343 void initDynamicSlot(uint32_t numFixed, uint32_t slot, const Value& value) {
1344 MOZ_ASSERT(numFixedSlots() == numFixed);
1345 MOZ_ASSERT(slot >= numFixed);
1346 MOZ_ASSERT(slot - numFixed < getSlotsHeader()->capacity());
1347 checkStoredValue(value);
1348 slots_[slot - numFixed].init(this, HeapSlot::Slot, slot, value);
1349 }
1350
1351 template <typename T>
1352 T* maybePtrFromReservedSlot(uint32_t slot) const {
1353 Value v = getReservedSlot(slot);
1354 return v.isUndefined() ? nullptr : static_cast<T*>(v.toPrivate());
1355 }
1356
1357 // Returns the address of a reserved fixed slot that stores a T* as
1358 // PrivateValue. Be very careful when using this because the object might be
1359 // moved in memory!
1360 template <typename T>
1361 T** addressOfFixedSlotPrivatePtr(size_t slot) {
1362 MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(getClass()));
1363 MOZ_ASSERT(slotIsFixed(slot));
1364 MOZ_ASSERT(getReservedSlot(slot).isDouble());
1365 void* addr = &getFixedSlotRef(slot);
1366 return reinterpret_cast<T**>(addr);
1367 }
1368
1369 /*
1370 * Calculate the number of dynamic slots to allocate to cover the properties
1371 * in an object with the given number of fixed slots and slot span.
1372 */
1373 static MOZ_ALWAYS_INLINE uint32_t calculateDynamicSlots(uint32_t nfixed,
1374 uint32_t span,
1375 const JSClass* clasp);
1376 static MOZ_ALWAYS_INLINE uint32_t calculateDynamicSlots(SharedShape* shape);
1377
1378 ObjectSlots* getSlotsHeader() const { return ObjectSlots::fromSlots(slots_); }
1379
1380 /* Elements accessors. */
1381
1382 // The maximum size, in sizeof(Value), of the allocation used for an
1383 // object's dense elements. (This includes space used to store an
1384 // ObjectElements instance.)
1385 // |MAX_DENSE_ELEMENTS_ALLOCATION * sizeof(JS::Value)| shouldn't overflow
1386 // int32_t (see elementsSizeMustNotOverflow).
1387 static const uint32_t MAX_DENSE_ELEMENTS_ALLOCATION = (1 << 28) - 1;
1388
1389 // The maximum number of usable dense elements in an object.
1390 static const uint32_t MAX_DENSE_ELEMENTS_COUNT =
1391 MAX_DENSE_ELEMENTS_ALLOCATION - ObjectElements::VALUES_PER_HEADER;
1392
1393 static void elementsSizeMustNotOverflow() {
1394 static_assert(
1395 NativeObject::MAX_DENSE_ELEMENTS_COUNT <= INT32_MAX / sizeof(JS::Value),
1396 "every caller of this method require that an element "
1397 "count multiplied by sizeof(Value) can't overflow "
1398 "uint32_t (and sometimes int32_t ,too)");
1399 }
1400
1401 ObjectElements* getElementsHeader() const {
1402 return ObjectElements::fromElements(elements_);
1403 }
1404
1405 // Returns a pointer to the first element, including shifted elements.
1406 inline HeapSlot* unshiftedElements() const {
1407 return elements_ - getElementsHeader()->numShiftedElements();
1408 }
1409
1410 // Like getElementsHeader, but returns a pointer to the unshifted header.
1411 // This is mainly useful for free()ing dynamic elements: the pointer
1412 // returned here is the one we got from malloc.
1413 void* getUnshiftedElementsHeader() const {
1414 return ObjectElements::fromElements(unshiftedElements());
1415 }
1416
1417 uint32_t unshiftedIndex(uint32_t index) const {
1418 return index + getElementsHeader()->numShiftedElements();
1419 }
1420
1421 /* Accessors for elements. */
1422 bool ensureElements(JSContext* cx, uint32_t capacity) {
1423 MOZ_ASSERT(isExtensible());
1424 if (capacity > getDenseCapacity()) {
1425 return growElements(cx, capacity);
1426 }
1427 return true;
1428 }
1429
1430 // Try to shift |count| dense elements, see the "Shifted elements" comment.
1431 inline bool tryShiftDenseElements(uint32_t count);
1432
1433 // Try to make space for |count| dense elements at the start of the array.
1434 bool tryUnshiftDenseElements(uint32_t count);
1435
1436 // Move the elements header and all shifted elements to the start of the
1437 // allocated elements space, so that numShiftedElements is 0 afterwards.
1438 void moveShiftedElements();
1439
1440 // If this object has many shifted elements call moveShiftedElements.
1441 void maybeMoveShiftedElements();
1442
1443 static bool goodElementsAllocationAmount(JSContext* cx, uint32_t reqAllocated,
1444 uint32_t length,
1445 uint32_t* goodAmount);
1446 bool growElements(JSContext* cx, uint32_t newcap);
1447 void shrinkElements(JSContext* cx, uint32_t cap);
1448
1449 private:
1450 // Run a post write barrier that encompasses multiple contiguous elements in a
1451 // single step.
1452 inline void elementsRangePostWriteBarrier(uint32_t start, uint32_t count);
1453
1454 public:
1455 void shrinkCapacityToInitializedLength(JSContext* cx);
1456
1457 private:
1458 void setDenseInitializedLengthInternal(uint32_t length) {
1459 MOZ_ASSERT(length <= getDenseCapacity());
1460 MOZ_ASSERT(!denseElementsAreFrozen());
1461 prepareElementRangeForOverwrite(length,
1462 getElementsHeader()->initializedLength);
1463 getElementsHeader()->initializedLength = length;
1464 }
1465
1466 public:
1467 void setDenseInitializedLength(uint32_t length) {
1468 MOZ_ASSERT(isExtensible());
1469 setDenseInitializedLengthInternal(length);
1470 }
1471
1472 void setDenseInitializedLengthMaybeNonExtensible(JSContext* cx,
1473 uint32_t length) {
1474 setDenseInitializedLengthInternal(length);
1475 if (!isExtensible()) {
1476 shrinkCapacityToInitializedLength(cx);
1477 }
1478 }
1479
1480 inline void ensureDenseInitializedLength(uint32_t index, uint32_t extra);
1481
1482 void setDenseElement(uint32_t index, const Value& val) {
1483 MOZ_ASSERT_IF(val.isMagic(), val.whyMagic() != JS_ELEMENTS_HOLE);
1484 setDenseElementUnchecked(index, val);
1485 }
1486
1487 void initDenseElement(uint32_t index, const Value& val) {
1488 MOZ_ASSERT(!val.isMagic(JS_ELEMENTS_HOLE));
1489 initDenseElementUnchecked(index, val);
1490 }
1491
1492 private:
1493 // Note: 'Unchecked' here means we don't assert |val| isn't the hole
1494 // MagicValue.
1495 void initDenseElementUnchecked(uint32_t index, const Value& val) {
1496 MOZ_ASSERT(index < getDenseInitializedLength());
1497 MOZ_ASSERT(isExtensible());
1498 checkStoredValue(val);
1499 elements_[index].init(this, HeapSlot::Element, unshiftedIndex(index), val);
1500 }
1501 void setDenseElementUnchecked(uint32_t index, const Value& val) {
1502 MOZ_ASSERT(index < getDenseInitializedLength());
1503 MOZ_ASSERT(!denseElementsAreFrozen());
1504 checkStoredValue(val);
1505 elements_[index].set(this, HeapSlot::Element, unshiftedIndex(index), val);
1506 }
1507
1508 // Mark the dense elements as possibly containing holes.
1509 inline void markDenseElementsNotPacked();
1510
1511 public:
1512 inline void initDenseElementHole(uint32_t index);
1513 inline void setDenseElementHole(uint32_t index);
1514 inline void removeDenseElementForSparseIndex(uint32_t index);
1515
1516 inline void copyDenseElements(uint32_t dstStart, const Value* src,
1517 uint32_t count);
1518
1519 inline void initDenseElements(const Value* src, uint32_t count);
1520 inline void initDenseElements(JSLinearString** src, uint32_t count);
1521 inline void initDenseElements(NativeObject* src, uint32_t srcStart,
1522 uint32_t count);
1523
1524 // Copy the first `count` dense elements from `src` to `this`, starting at
1525 // `destStart`. The initialized length must already include the new elements.
1526 inline void initDenseElementRange(uint32_t destStart, NativeObject* src,
1527 uint32_t count);
1528
1529 // Store the Values in the range [begin, end) as elements of this array.
1530 //
1531 // Preconditions: This must be a boring ArrayObject with dense initialized
1532 // length 0: no shifted elements, no frozen elements, no fixed "length", not
1533 // indexed, not inextensible, not copy-on-write. Existing capacity is
1534 // optional.
1535 //
1536 // This runs write barriers but does not update types. `end - begin` must
1537 // return the size of the range, which must be >= 0 and fit in an int32_t.
1538 template <typename Iter>
1539 [[nodiscard]] inline bool initDenseElementsFromRange(JSContext* cx,
1540 Iter begin, Iter end);
1541
1542 inline void moveDenseElements(uint32_t dstStart, uint32_t srcStart,
1543 uint32_t count);
1544 inline void reverseDenseElementsNoPreBarrier(uint32_t length);
1545
1546 inline DenseElementResult setOrExtendDenseElements(JSContext* cx,
1547 uint32_t start,
1548 const Value* vp,
1549 uint32_t count);
1550
1551 bool denseElementsAreSealed() const {
1552 return getElementsHeader()->isSealed();
1553 }
1554 bool denseElementsAreFrozen() const {
1555 return hasFlag(ObjectFlag::FrozenElements);
1556 }
1557
1558 bool denseElementsArePacked() const {
1559 return getElementsHeader()->isPacked();
1560 }
1561
1562 void markDenseElementsMaybeInIteration() {
1563 getElementsHeader()->markMaybeInIteration();
1564 }
1565
1566 // Return whether the object's dense elements might be in the midst of for-in
1567 // iteration. We rely on this to be able to safely delete or move dense array
1568 // elements without worrying about updating in-progress iterators.
1569 // See bug 690622.
1570 //
1571 // Note that it's fine to return false if this object is on the prototype of
1572 // another object: SuppressDeletedProperty only suppresses properties deleted
1573 // from the iterated object itself.
1574 inline bool denseElementsHaveMaybeInIterationFlag();
1575 inline bool denseElementsMaybeInIteration();
1576
1577 // Ensures that the object can hold at least index + extra elements. This
1578 // returns DenseElement_Success on success, DenseElement_Failed on failure
1579 // to grow the array, or DenseElement_Incomplete when the object is too
1580 // sparse to grow (this includes the case of index + extra overflow). In
1581 // the last two cases the object is kept intact.
1582 inline DenseElementResult ensureDenseElements(JSContext* cx, uint32_t index,
1583 uint32_t extra);
1584
1585 inline DenseElementResult extendDenseElements(JSContext* cx,
1586 uint32_t requiredCapacity,
1587 uint32_t extra);
1588
1589 /* Small objects are dense, no matter what. */
1590 static const uint32_t MIN_SPARSE_INDEX = 1000;
1591
1592 /*
1593 * Element storage for an object will be sparse if fewer than 1/8 indexes
1594 * are filled in.
1595 */
1596 static const unsigned SPARSE_DENSITY_RATIO = 8;
1597
1598 /*
1599 * Check if after growing the object's elements will be too sparse.
1600 * newElementsHint is an estimated number of elements to be added.
1601 */
1602 bool willBeSparseElements(uint32_t requiredCapacity,
1603 uint32_t newElementsHint);
1604
1605 /*
1606 * After adding a sparse index to obj, see if it should be converted to use
1607 * dense elements.
1608 */
1609 static DenseElementResult maybeDensifySparseElements(
1610 JSContext* cx, Handle<NativeObject*> obj);
1611 static bool densifySparseElements(JSContext* cx, Handle<NativeObject*> obj);
1612
1613 inline HeapSlot* fixedElements() const {
1614 static_assert(2 * sizeof(Value) == sizeof(ObjectElements),
1615 "when elements are stored inline, the first two "
1616 "slots will hold the ObjectElements header");
1617 return &fixedSlots()[2];
1618 }
1619
1620 #ifdef DEBUG
1621 bool canHaveNonEmptyElements();
1622 #endif
1623
1624 void setEmptyElements() { elements_ = emptyObjectElements; }
1625
1626 void initFixedElements(gc::AllocKind kind, uint32_t length);
1627
1628 // Update the elements pointer to use the fixed elements storage. The caller
1629 // is responsible for initializing the elements themselves and setting the
1630 // FIXED flag.
1631 void setFixedElements(uint32_t numShifted = 0) {
1632 MOZ_ASSERT(canHaveNonEmptyElements());
1633 elements_ = fixedElements() + numShifted;
1634 }
1635
1636 inline bool hasDynamicElements() const {
1637 return !hasEmptyElements() && !hasFixedElements();
1638 }
1639
1640 inline bool hasFixedElements() const {
1641 bool fixed = getElementsHeader()->flags & ObjectElements::FIXED;
1642 MOZ_ASSERT_IF(fixed, unshiftedElements() == fixedElements());
1643 return fixed;
1644 }
1645
1646 inline bool hasEmptyElements() const {
1647 return elements_ == emptyObjectElements ||
1648 elements_ == emptyObjectElementsShared;
1649 }
1650
1651 /*
1652 * Get a pointer to the unused data in the object's allocation immediately
1653 * following this object, for use with objects which allocate a larger size
1654 * class than they need and store non-elements data inline.
1655 */
1656 inline uint8_t* fixedData(size_t nslots) const;
1657
1658 inline void privatePreWriteBarrier(HeapSlot* pprivate);
1659
1660 // The methods below are used to store GC things in a reserved slot as
1661 // PrivateValues. This is done to bypass the normal tracing code (debugger
1662 // objects use this to store cross-compartment pointers).
1663 //
1664 // WARNING: make sure you REALLY need this and you know what you're doing
1665 // before using these methods!
1666 void setReservedSlotGCThingAsPrivate(uint32_t slot, gc::Cell* cell) {
1667 #ifdef DEBUG
1668 if (IsMarkedBlack(this)) {
1669 JS::AssertCellIsNotGray(cell);
1670 }
1671 #endif
1672 HeapSlot* pslot = getSlotAddress(slot);
1673 Cell* prev = nullptr;
1674 if (!pslot->isUndefined()) {
1675 prev = static_cast<gc::Cell*>(pslot->toPrivate());
1676 privatePreWriteBarrier(pslot);
1677 }
1678 setReservedSlotGCThingAsPrivateUnbarriered(slot, cell);
1679 gc::PostWriteBarrierCell(this, prev, cell);
1680 }
1681 void setReservedSlotGCThingAsPrivateUnbarriered(uint32_t slot,
1682 gc::Cell* cell) {
1683 MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(getClass()));
1684 MOZ_ASSERT(cell);
1685 getReservedSlotRef(slot).unbarrieredSet(PrivateValue(cell));
1686 }
1687 void clearReservedSlotGCThingAsPrivate(uint32_t slot) {
1688 MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(getClass()));
1689 HeapSlot* pslot = &getReservedSlotRef(slot);
1690 if (!pslot->isUndefined()) {
1691 privatePreWriteBarrier(pslot);
1692 pslot->unbarrieredSet(UndefinedValue());
1693 }
1694 }
1695
1696 // This is equivalent to |setReservedSlot(slot, PrivateValue(v))| but it
1697 // avoids GC barriers. Use this only when storing a private value in a
1698 // reserved slot that never holds a GC thing.
1699 void setReservedSlotPrivateUnbarriered(uint32_t slot, void* v) {
1700 MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(getClass()));
1701 MOZ_ASSERT(getReservedSlot(slot).isUndefined() ||
1702 getReservedSlot(slot).isDouble());
1703 getReservedSlotRef(slot).unbarrieredSet(PrivateValue(v));
1704 }
1705
1706 // Like setReservedSlotPrivateUnbarriered but for PrivateUint32Value.
1707 void setReservedSlotPrivateUint32Unbarriered(uint32_t slot, uint32_t u) {
1708 MOZ_ASSERT(slot < JSCLASS_RESERVED_SLOTS(getClass()));
1709 MOZ_ASSERT(getReservedSlot(slot).isUndefined() ||
1710 getReservedSlot(slot).isInt32());
1711 getReservedSlotRef(slot).unbarrieredSet(PrivateUint32Value(u));
1712 }
1713
1714 /* Return the allocKind we would use if we were to tenure this object. */
1715 inline js::gc::AllocKind allocKindForTenure() const;
1716
1717 // Native objects are never wrappers, so a native object always has a realm
1718 // and global.
1719 JS::Realm* realm() const { return nonCCWRealm(); }
1720 inline js::GlobalObject& global() const;
1721
1722 TaggedSlotOffset getTaggedSlotOffset(size_t slot) const {
1723 MOZ_ASSERT(slot < slotSpan());
1724 uint32_t nfixed = numFixedSlots();
1725 if (slot < nfixed) {
1726 return TaggedSlotOffset(getFixedSlotOffset(slot),
1727 /* isFixedSlot = */ true);
1728 }
1729 return TaggedSlotOffset((slot - nfixed) * sizeof(Value),
1730 /* isFixedSlot = */ false);
1731 }
1732
1733 /* JIT Accessors */
1734 static size_t offsetOfElements() { return offsetof(NativeObject, elements_); }
1735 static size_t offsetOfFixedElements() {
1736 return sizeof(NativeObject) + sizeof(ObjectElements);
1737 }
1738
1739 static constexpr size_t getFixedSlotOffset(size_t slot) {
1740 MOZ_ASSERT(slot < MAX_FIXED_SLOTS);
1741 return sizeof(NativeObject) + slot * sizeof(Value);
1742 }
1743 static constexpr size_t getFixedSlotIndexFromOffset(size_t offset) {
1744 MOZ_ASSERT(offset >= sizeof(NativeObject));
1745 offset -= sizeof(NativeObject);
1746 MOZ_ASSERT(offset % sizeof(Value) == 0);
1747 MOZ_ASSERT(offset / sizeof(Value) < MAX_FIXED_SLOTS);
1748 return offset / sizeof(Value);
1749 }
1750 static constexpr size_t getDynamicSlotIndexFromOffset(size_t offset) {
1751 MOZ_ASSERT(offset % sizeof(Value) == 0);
1752 return offset / sizeof(Value);
1753 }
1754 static size_t offsetOfSlots() { return offsetof(NativeObject, slots_); }
1755 };
1756
1757 inline void NativeObject::privatePreWriteBarrier(HeapSlot* pprivate) {
1758 JS::shadow::Zone* shadowZone = this->shadowZoneFromAnyThread();
1759 if (shadowZone->needsIncrementalBarrier() && pprivate->get().toPrivate() &&
1760 getClass()->hasTrace()) {
1761 getClass()->doTrace(shadowZone->barrierTracer(), this);
1762 }
1763 }
1764
1765 /*** Standard internal methods **********************************************/
1766
1767 /*
1768 * These functions should follow the algorithms in ES2025 section 10.1
1769 * ("Ordinary Object Internal Methods").
1770 *
1771 * Many native objects are not "ordinary" in ES2025, so these functions also
1772 * have to serve some of the special needs of Arrays (10.4.2), Strings (10.4.3),
1773 * and so on.
1774 */
1775
1776 extern bool NativeDefineProperty(JSContext* cx, Handle<NativeObject*> obj,
1777 HandleId id,
1778 Handle<JS::PropertyDescriptor> desc,
1779 ObjectOpResult& result);
1780
1781 extern bool NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1782 HandleId id, HandleValue value,
1783 unsigned attrs, ObjectOpResult& result);
1784
1785 /* If the result out-param is omitted, throw on failure. */
1786
1787 extern bool NativeDefineAccessorProperty(JSContext* cx,
1788 Handle<NativeObject*> obj, HandleId id,
1789 HandleObject getter,
1790 HandleObject setter, unsigned attrs);
1791
1792 extern bool NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1793 HandleId id, HandleValue value,
1794 unsigned attrs);
1795
1796 extern bool NativeDefineDataProperty(JSContext* cx, Handle<NativeObject*> obj,
1797 PropertyName* name, HandleValue value,
1798 unsigned attrs);
1799
1800 extern bool NativeHasProperty(JSContext* cx, Handle<NativeObject*> obj,
1801 HandleId id, bool* foundp);
1802
1803 extern bool NativeGetOwnPropertyDescriptor(
1804 JSContext* cx, Handle<NativeObject*> obj, HandleId id,
1805 MutableHandle<mozilla::Maybe<JS::PropertyDescriptor>> desc);
1806
1807 extern bool NativeGetProperty(JSContext* cx, Handle<NativeObject*> obj,
1808 HandleValue receiver, HandleId id,
1809 MutableHandleValue vp);
1810
1811 extern bool NativeGetPropertyNoGC(JSContext* cx, NativeObject* obj,
1812 const Value& receiver, jsid id, Value* vp);
1813
1814 inline bool NativeGetProperty(JSContext* cx, Handle<NativeObject*> obj,
1815 HandleId id, MutableHandleValue vp) {
1816 RootedValue receiver(cx, ObjectValue(*obj));
1817 return NativeGetProperty(cx, obj, receiver, id, vp);
1818 }
1819
1820 extern bool NativeGetElement(JSContext* cx, Handle<NativeObject*> obj,
1821 HandleValue receiver, int32_t index,
1822 MutableHandleValue vp);
1823
1824 bool GetSparseElementHelper(JSContext* cx, Handle<NativeObject*> obj,
1825 int32_t int_id, MutableHandleValue result);
1826
1827 bool AddOrUpdateSparseElementHelper(JSContext* cx, Handle<NativeObject*> obj,
1828 int32_t int_id, HandleValue v, bool strict);
1829
1830 /*
1831 * Indicates whether an assignment operation is qualified (`x.y = 0`) or
1832 * unqualified (`y = 0`). In strict mode, the latter is an error if no such
1833 * variable already exists.
1834 *
1835 * Used as an argument to NativeSetProperty.
1836 */
1837 enum QualifiedBool { Unqualified = 0, Qualified = 1 };
1838
1839 template <QualifiedBool Qualified>
1840 extern bool NativeSetProperty(JSContext* cx, Handle<NativeObject*> obj,
1841 HandleId id, HandleValue v, HandleValue receiver,
1842 ObjectOpResult& result);
1843
1844 extern bool NativeSetElement(JSContext* cx, Handle<NativeObject*> obj,
1845 uint32_t index, HandleValue v,
1846 HandleValue receiver, ObjectOpResult& result);
1847
1848 extern bool NativeDeleteProperty(JSContext* cx, Handle<NativeObject*> obj,
1849 HandleId id, ObjectOpResult& result);
1850
1851 /*** SpiderMonkey nonstandard internal methods ******************************/
1852
1853 template <AllowGC allowGC>
1854 extern bool NativeLookupOwnProperty(
1855 JSContext* cx, typename MaybeRooted<NativeObject*, allowGC>::HandleType obj,
1856 typename MaybeRooted<jsid, allowGC>::HandleType id, PropertyResult* propp);
1857
1858 /*
1859 * Get a property from `receiver`, after having already done a lookup and found
1860 * the property on a native object `obj`.
1861 *
1862 * `prop` must be present in obj's shape.
1863 */
1864 extern bool NativeGetExistingProperty(JSContext* cx, HandleObject receiver,
1865 Handle<NativeObject*> obj, HandleId id,
1866 PropertyInfo prop, MutableHandleValue vp);
1867
1868 /* * */
1869
1870 extern bool GetNameBoundInEnvironment(JSContext* cx, HandleObject env,
1871 HandleId id, MutableHandleValue vp);
1872
1873 } /* namespace js */
1874
1875 template <>
1876 inline bool JSObject::is<js::NativeObject>() const {
1877 return shape()->isNative();
1878 }
1879
1880 namespace js {
1881
1882 // Alternate to JSObject::as<NativeObject>() that tolerates null pointers.
1883 inline NativeObject* MaybeNativeObject(JSObject* obj) {
1884 return obj ? &obj->as<NativeObject>() : nullptr;
1885 }
1886
1887 // Defined in NativeObject-inl.h.
1888 bool IsPackedArray(JSObject* obj);
1889
1890 // Initialize an object's reserved slot with a private value pointing to
1891 // malloc-allocated memory and associate the memory with the object.
1892 //
1893 // This call should be matched with a call to JS::GCContext::free_/delete_ in
1894 // the object's finalizer to free the memory and update the memory accounting.
1895
1896 inline void InitReservedSlot(NativeObject* obj, uint32_t slot, void* ptr,
1897 size_t nbytes, MemoryUse use) {
1898 AddCellMemory(obj, nbytes, use);
1899 obj->initReservedSlot(slot, PrivateValue(ptr));
1900 }
1901 template <typename T>
1902 inline void InitReservedSlot(NativeObject* obj, uint32_t slot, T* ptr,
1903 MemoryUse use) {
1904 InitReservedSlot(obj, slot, ptr, sizeof(T), use);
1905 }
1906
1907 bool AddSlotAndCallAddPropHook(JSContext* cx, Handle<NativeObject*> obj,
1908 HandleValue v, Handle<Shape*> newShape);
1909
1910 } // namespace js
1911
1912 #endif /* vm_NativeObject_h */