[SM91] Update to Spidermonkey 91.1.3 APIs
[0ad.git] / libraries / source / spidermonkey / include-win32-release / js / RootingAPI.h
blobd19c63fec854c4cdd33c58e254de9c64f4a00bbd
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/. */
7 #ifndef js_RootingAPI_h
8 #define js_RootingAPI_h
10 #include "mozilla/Attributes.h"
11 #include "mozilla/DebugOnly.h"
12 #include "mozilla/EnumeratedArray.h"
13 #include "mozilla/LinkedList.h"
14 #include "mozilla/Maybe.h"
16 #include <type_traits>
17 #include <utility>
19 #include "jspubtd.h"
21 #include "js/ComparisonOperators.h" // JS::detail::DefineComparisonOps
22 #include "js/GCAnnotations.h"
23 #include "js/GCPolicyAPI.h"
24 #include "js/GCTypeMacros.h" // JS_FOR_EACH_PUBLIC_{,TAGGED_}GC_POINTER_TYPE
25 #include "js/HashTable.h"
26 #include "js/HeapAPI.h"
27 #include "js/ProfilingStack.h"
28 #include "js/Realm.h"
29 #include "js/TypeDecls.h"
30 #include "js/UniquePtr.h"
33 * [SMDOC] Stack Rooting
35 * Moving GC Stack Rooting
37 * A moving GC may change the physical location of GC allocated things, even
38 * when they are rooted, updating all pointers to the thing to refer to its new
39 * location. The GC must therefore know about all live pointers to a thing,
40 * not just one of them, in order to behave correctly.
42 * The |Rooted| and |Handle| classes below are used to root stack locations
43 * whose value may be held live across a call that can trigger GC. For a
44 * code fragment such as:
46 * JSObject* obj = NewObject(cx);
47 * DoSomething(cx);
48 * ... = obj->lastProperty();
50 * If |DoSomething()| can trigger a GC, the stack location of |obj| must be
51 * rooted to ensure that the GC does not move the JSObject referred to by
52 * |obj| without updating |obj|'s location itself. This rooting must happen
53 * regardless of whether there are other roots which ensure that the object
54 * itself will not be collected.
56 * If |DoSomething()| cannot trigger a GC, and the same holds for all other
57 * calls made between |obj|'s definitions and its last uses, then no rooting
58 * is required.
60 * SpiderMonkey can trigger a GC at almost any time and in ways that are not
61 * always clear. For example, the following innocuous-looking actions can
62 * cause a GC: allocation of any new GC thing; JSObject::hasProperty;
63 * JS_ReportError and friends; and ToNumber, among many others. The following
64 * dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_,
65 * rt->malloc_, and friends and JS_ReportOutOfMemory.
67 * The following family of three classes will exactly root a stack location.
68 * Incorrect usage of these classes will result in a compile error in almost
69 * all cases. Therefore, it is very hard to be incorrectly rooted if you use
70 * these classes exclusively. These classes are all templated on the type T of
71 * the value being rooted.
73 * - Rooted<T> declares a variable of type T, whose value is always rooted.
74 * Rooted<T> may be automatically coerced to a Handle<T>, below. Rooted<T>
75 * should be used whenever a local variable's value may be held live across a
76 * call which can trigger a GC.
78 * - Handle<T> is a const reference to a Rooted<T>. Functions which take GC
79 * things or values as arguments and need to root those arguments should
80 * generally use handles for those arguments and avoid any explicit rooting.
81 * This has two benefits. First, when several such functions call each other
82 * then redundant rooting of multiple copies of the GC thing can be avoided.
83 * Second, if the caller does not pass a rooted value a compile error will be
84 * generated, which is quicker and easier to fix than when relying on a
85 * separate rooting analysis.
87 * - MutableHandle<T> is a non-const reference to Rooted<T>. It is used in the
88 * same way as Handle<T> and includes a |set(const T& v)| method to allow
89 * updating the value of the referenced Rooted<T>. A MutableHandle<T> can be
90 * created with an implicit cast from a Rooted<T>*.
92 * In some cases the small performance overhead of exact rooting (measured to
93 * be a few nanoseconds on desktop) is too much. In these cases, try the
94 * following:
96 * - Move all Rooted<T> above inner loops: this allows you to re-use the root
97 * on each iteration of the loop.
99 * - Pass Handle<T> through your hot call stack to avoid re-rooting costs at
100 * every invocation.
102 * The following diagram explains the list of supported, implicit type
103 * conversions between classes of this family:
105 * Rooted<T> ----> Handle<T>
106 * | ^
107 * | |
108 * | |
109 * +---> MutableHandle<T>
110 * (via &)
112 * All of these types have an implicit conversion to raw pointers.
115 namespace js {
117 template <typename T>
118 struct BarrierMethods {};
120 template <typename Element, typename Wrapper>
121 class WrappedPtrOperations {};
123 template <typename Element, typename Wrapper>
124 class MutableWrappedPtrOperations
125 : public WrappedPtrOperations<Element, Wrapper> {};
127 template <typename T, typename Wrapper>
128 class RootedBase : public MutableWrappedPtrOperations<T, Wrapper> {};
130 template <typename T, typename Wrapper>
131 class HandleBase : public WrappedPtrOperations<T, Wrapper> {};
133 template <typename T, typename Wrapper>
134 class MutableHandleBase : public MutableWrappedPtrOperations<T, Wrapper> {};
136 template <typename T, typename Wrapper>
137 class HeapBase : public MutableWrappedPtrOperations<T, Wrapper> {};
139 // Cannot use FOR_EACH_HEAP_ABLE_GC_POINTER_TYPE, as this would import too many
140 // macros into scope
141 template <typename T>
142 struct IsHeapConstructibleType {
143 static constexpr bool value = false;
145 #define DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE(T) \
146 template <> \
147 struct IsHeapConstructibleType<T> { \
148 static constexpr bool value = true; \
150 JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE)
151 JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE)
152 #undef DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE
154 namespace gc {
155 struct Cell;
156 } /* namespace gc */
158 // Important: Return a reference so passing a Rooted<T>, etc. to
159 // something that takes a |const T&| is not a GC hazard.
160 #define DECLARE_POINTER_CONSTREF_OPS(T) \
161 operator const T&() const { return get(); } \
162 const T& operator->() const { return get(); }
164 // Assignment operators on a base class are hidden by the implicitly defined
165 // operator= on the derived class. Thus, define the operator= directly on the
166 // class as we would need to manually pass it through anyway.
167 #define DECLARE_POINTER_ASSIGN_OPS(Wrapper, T) \
168 Wrapper<T>& operator=(const T& p) { \
169 set(p); \
170 return *this; \
172 Wrapper<T>& operator=(T&& p) { \
173 set(std::move(p)); \
174 return *this; \
176 Wrapper<T>& operator=(const Wrapper<T>& other) { \
177 set(other.get()); \
178 return *this; \
181 #define DELETE_ASSIGNMENT_OPS(Wrapper, T) \
182 template <typename S> \
183 Wrapper<T>& operator=(S) = delete; \
184 Wrapper<T>& operator=(const Wrapper<T>&) = delete;
186 #define DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr) \
187 const T* address() const { return &(ptr); } \
188 const T& get() const { return (ptr); }
190 #define DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr) \
191 T* address() { return &(ptr); } \
192 T& get() { return (ptr); }
194 } /* namespace js */
196 namespace JS {
198 JS_PUBLIC_API void HeapObjectPostWriteBarrier(JSObject** objp, JSObject* prev,
199 JSObject* next);
200 JS_PUBLIC_API void HeapStringPostWriteBarrier(JSString** objp, JSString* prev,
201 JSString* next);
202 JS_PUBLIC_API void HeapBigIntPostWriteBarrier(JS::BigInt** bip,
203 JS::BigInt* prev,
204 JS::BigInt* next);
205 JS_PUBLIC_API void HeapObjectWriteBarriers(JSObject** objp, JSObject* prev,
206 JSObject* next);
207 JS_PUBLIC_API void HeapStringWriteBarriers(JSString** objp, JSString* prev,
208 JSString* next);
209 JS_PUBLIC_API void HeapBigIntWriteBarriers(JS::BigInt** bip, JS::BigInt* prev,
210 JS::BigInt* next);
211 JS_PUBLIC_API void HeapScriptWriteBarriers(JSScript** objp, JSScript* prev,
212 JSScript* next);
215 * Create a safely-initialized |T|, suitable for use as a default value in
216 * situations requiring a safe but arbitrary |T| value.
218 template <typename T>
219 inline T SafelyInitialized() {
220 // This function wants to presume that |T()| -- which value-initializes a
221 // |T| per C++11 [expr.type.conv]p2 -- will produce a safely-initialized,
222 // safely-usable T that it can return.
224 #if defined(XP_WIN) || defined(XP_MACOSX) || \
225 (defined(XP_UNIX) && !defined(__clang__))
227 // That presumption holds for pointers, where value initialization produces
228 // a null pointer.
229 constexpr bool IsPointer = std::is_pointer_v<T>;
231 // For classes and unions we *assume* that if |T|'s default constructor is
232 // non-trivial it'll initialize correctly. (This is unideal, but C++
233 // doesn't offer a type trait indicating whether a class's constructor is
234 // user-defined, which better approximates our desired semantics.)
235 constexpr bool IsNonTriviallyDefaultConstructibleClassOrUnion =
236 (std::is_class_v<T> ||
237 std::is_union_v<T>)&&!std::is_trivially_default_constructible_v<T>;
239 static_assert(IsPointer || IsNonTriviallyDefaultConstructibleClassOrUnion,
240 "T() must evaluate to a safely-initialized T");
242 #endif
244 return T();
247 #ifdef JS_DEBUG
249 * For generational GC, assert that an object is in the tenured generation as
250 * opposed to being in the nursery.
252 extern JS_PUBLIC_API void AssertGCThingMustBeTenured(JSObject* obj);
253 extern JS_PUBLIC_API void AssertGCThingIsNotNurseryAllocable(
254 js::gc::Cell* cell);
255 #else
256 inline void AssertGCThingMustBeTenured(JSObject* obj) {}
257 inline void AssertGCThingIsNotNurseryAllocable(js::gc::Cell* cell) {}
258 #endif
261 * The Heap<T> class is a heap-stored reference to a JS GC thing for use outside
262 * the JS engine. All members of heap classes that refer to GC things should use
263 * Heap<T> (or possibly TenuredHeap<T>, described below).
265 * Heap<T> is an abstraction that hides some of the complexity required to
266 * maintain GC invariants for the contained reference. It uses operator
267 * overloading to provide a normal pointer interface, but adds barriers to
268 * notify the GC of changes.
270 * Heap<T> implements the following barriers:
272 * - Post-write barrier (necessary for generational GC).
273 * - Read barrier (necessary for incremental GC and cycle collector
274 * integration).
276 * Note Heap<T> does not have a pre-write barrier as used internally in the
277 * engine. The read barrier is used to mark anything read from a Heap<T> during
278 * an incremental GC.
280 * Heap<T> may be moved or destroyed outside of GC finalization and hence may be
281 * used in dynamic storage such as a Vector.
283 * Heap<T> instances must be traced when their containing object is traced to
284 * keep the pointed-to GC thing alive.
286 * Heap<T> objects should only be used on the heap. GC references stored on the
287 * C/C++ stack must use Rooted/Handle/MutableHandle instead.
289 * Type T must be a public GC pointer type.
291 template <typename T>
292 class MOZ_NON_MEMMOVABLE Heap : public js::HeapBase<T, Heap<T>> {
293 // Please note: this can actually also be used by nsXBLMaybeCompiled<T>, for
294 // legacy reasons.
295 static_assert(js::IsHeapConstructibleType<T>::value,
296 "Type T must be a public GC pointer type");
298 public:
299 using ElementType = T;
301 Heap() : ptr(SafelyInitialized<T>()) {
302 // No barriers are required for initialization to the default value.
303 static_assert(sizeof(T) == sizeof(Heap<T>),
304 "Heap<T> must be binary compatible with T.");
306 explicit Heap(const T& p) { init(p); }
309 * For Heap, move semantics are equivalent to copy semantics. However, we want
310 * the copy constructor to be explicit, and an explicit move constructor
311 * breaks common usage of move semantics, so we need to define both, even
312 * though they are equivalent.
314 explicit Heap(const Heap<T>& other) { init(other.ptr); }
315 Heap(Heap<T>&& other) { init(other.ptr); }
317 Heap& operator=(Heap<T>&& other) {
318 set(other.unbarrieredGet());
319 other.set(SafelyInitialized<T>());
320 return *this;
323 ~Heap() { postWriteBarrier(ptr, SafelyInitialized<T>()); }
325 DECLARE_POINTER_CONSTREF_OPS(T);
326 DECLARE_POINTER_ASSIGN_OPS(Heap, T);
328 const T* address() const { return &ptr; }
330 void exposeToActiveJS() const { js::BarrierMethods<T>::exposeToJS(ptr); }
331 const T& get() const {
332 exposeToActiveJS();
333 return ptr;
335 const T& unbarrieredGet() const { return ptr; }
337 void set(const T& newPtr) {
338 T tmp = ptr;
339 ptr = newPtr;
340 postWriteBarrier(tmp, ptr);
343 T* unsafeGet() { return &ptr; }
345 void unbarrieredSet(const T& newPtr) { ptr = newPtr; }
347 explicit operator bool() const {
348 return bool(js::BarrierMethods<T>::asGCThingOrNull(ptr));
350 explicit operator bool() {
351 return bool(js::BarrierMethods<T>::asGCThingOrNull(ptr));
354 private:
355 void init(const T& newPtr) {
356 ptr = newPtr;
357 postWriteBarrier(SafelyInitialized<T>(), ptr);
360 void postWriteBarrier(const T& prev, const T& next) {
361 js::BarrierMethods<T>::postWriteBarrier(&ptr, prev, next);
364 T ptr;
367 namespace detail {
369 template <typename T>
370 struct DefineComparisonOps<Heap<T>> : std::true_type {
371 static const T& get(const Heap<T>& v) { return v.unbarrieredGet(); }
374 } // namespace detail
376 static MOZ_ALWAYS_INLINE bool ObjectIsTenured(JSObject* obj) {
377 return !js::gc::IsInsideNursery(reinterpret_cast<js::gc::Cell*>(obj));
380 static MOZ_ALWAYS_INLINE bool ObjectIsTenured(const Heap<JSObject*>& obj) {
381 return ObjectIsTenured(obj.unbarrieredGet());
384 static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(JSObject* obj) {
385 auto cell = reinterpret_cast<js::gc::Cell*>(obj);
386 return js::gc::detail::CellIsMarkedGrayIfKnown(cell);
389 static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(
390 const JS::Heap<JSObject*>& obj) {
391 return ObjectIsMarkedGray(obj.unbarrieredGet());
394 // The following *IsNotGray functions take account of the eventual
395 // gray marking state at the end of any ongoing incremental GC by
396 // delaying the checks if necessary.
398 #ifdef DEBUG
400 inline void AssertCellIsNotGray(const js::gc::Cell* maybeCell) {
401 if (maybeCell) {
402 js::gc::detail::AssertCellIsNotGray(maybeCell);
406 inline void AssertObjectIsNotGray(JSObject* maybeObj) {
407 AssertCellIsNotGray(reinterpret_cast<js::gc::Cell*>(maybeObj));
410 inline void AssertObjectIsNotGray(const JS::Heap<JSObject*>& obj) {
411 AssertObjectIsNotGray(obj.unbarrieredGet());
414 #else
416 inline void AssertCellIsNotGray(js::gc::Cell* maybeCell) {}
417 inline void AssertObjectIsNotGray(JSObject* maybeObj) {}
418 inline void AssertObjectIsNotGray(const JS::Heap<JSObject*>& obj) {}
420 #endif
423 * The TenuredHeap<T> class is similar to the Heap<T> class above in that it
424 * encapsulates the GC concerns of an on-heap reference to a JS object. However,
425 * it has two important differences:
427 * 1) Pointers which are statically known to only reference "tenured" objects
428 * can avoid the extra overhead of SpiderMonkey's write barriers.
430 * 2) Objects in the "tenured" heap have stronger alignment restrictions than
431 * those in the "nursery", so it is possible to store flags in the lower
432 * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged
433 * pointer with a nice API for accessing the flag bits and adds various
434 * assertions to ensure that it is not mis-used.
436 * GC things are said to be "tenured" when they are located in the long-lived
437 * heap: e.g. they have gained tenure as an object by surviving past at least
438 * one GC. For performance, SpiderMonkey allocates some things which are known
439 * to normally be long lived directly into the tenured generation; for example,
440 * global objects. Additionally, SpiderMonkey does not visit individual objects
441 * when deleting non-tenured objects, so object with finalizers are also always
442 * tenured; for instance, this includes most DOM objects.
444 * The considerations to keep in mind when using a TenuredHeap<T> vs a normal
445 * Heap<T> are:
447 * - It is invalid for a TenuredHeap<T> to refer to a non-tenured thing.
448 * - It is however valid for a Heap<T> to refer to a tenured thing.
449 * - It is not possible to store flag bits in a Heap<T>.
451 template <typename T>
452 class TenuredHeap : public js::HeapBase<T, TenuredHeap<T>> {
453 public:
454 using ElementType = T;
456 TenuredHeap() : bits(0) {
457 static_assert(sizeof(T) == sizeof(TenuredHeap<T>),
458 "TenuredHeap<T> must be binary compatible with T.");
460 explicit TenuredHeap(T p) : bits(0) { setPtr(p); }
461 explicit TenuredHeap(const TenuredHeap<T>& p) : bits(0) {
462 setPtr(p.getPtr());
465 void setPtr(T newPtr) {
466 MOZ_ASSERT((reinterpret_cast<uintptr_t>(newPtr) & flagsMask) == 0);
467 MOZ_ASSERT(js::gc::IsCellPointerValidOrNull(newPtr));
468 if (newPtr) {
469 AssertGCThingMustBeTenured(newPtr);
471 bits = (bits & flagsMask) | reinterpret_cast<uintptr_t>(newPtr);
474 void setFlags(uintptr_t flagsToSet) {
475 MOZ_ASSERT((flagsToSet & ~flagsMask) == 0);
476 bits |= flagsToSet;
479 void unsetFlags(uintptr_t flagsToUnset) {
480 MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0);
481 bits &= ~flagsToUnset;
484 bool hasFlag(uintptr_t flag) const {
485 MOZ_ASSERT((flag & ~flagsMask) == 0);
486 return (bits & flag) != 0;
489 T unbarrieredGetPtr() const { return reinterpret_cast<T>(bits & ~flagsMask); }
490 uintptr_t getFlags() const { return bits & flagsMask; }
492 void exposeToActiveJS() const {
493 js::BarrierMethods<T>::exposeToJS(unbarrieredGetPtr());
495 T getPtr() const {
496 exposeToActiveJS();
497 return unbarrieredGetPtr();
500 operator T() const { return getPtr(); }
501 T operator->() const { return getPtr(); }
503 explicit operator bool() const {
504 return bool(js::BarrierMethods<T>::asGCThingOrNull(unbarrieredGetPtr()));
506 explicit operator bool() {
507 return bool(js::BarrierMethods<T>::asGCThingOrNull(unbarrieredGetPtr()));
510 TenuredHeap<T>& operator=(T p) {
511 setPtr(p);
512 return *this;
515 TenuredHeap<T>& operator=(const TenuredHeap<T>& other) {
516 bits = other.bits;
517 return *this;
520 private:
521 enum {
522 maskBits = 3,
523 flagsMask = (1 << maskBits) - 1,
526 uintptr_t bits;
529 namespace detail {
531 template <typename T>
532 struct DefineComparisonOps<TenuredHeap<T>> : std::true_type {
533 static const T get(const TenuredHeap<T>& v) { return v.unbarrieredGetPtr(); }
536 } // namespace detail
538 // std::swap uses a stack temporary, which prevents classes like Heap<T>
539 // from being declared MOZ_HEAP_CLASS.
540 template <typename T>
541 void swap(TenuredHeap<T>& aX, TenuredHeap<T>& aY) {
542 T tmp = aX;
543 aX = aY;
544 aY = tmp;
547 template <typename T>
548 void swap(Heap<T>& aX, Heap<T>& aY) {
549 T tmp = aX;
550 aX = aY;
551 aY = tmp;
554 static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(
555 const JS::TenuredHeap<JSObject*>& obj) {
556 return ObjectIsMarkedGray(obj.unbarrieredGetPtr());
559 template <typename T>
560 class MutableHandle;
561 template <typename T>
562 class Rooted;
563 template <typename T>
564 class PersistentRooted;
567 * Reference to a T that has been rooted elsewhere. This is most useful
568 * as a parameter type, which guarantees that the T lvalue is properly
569 * rooted. See "Move GC Stack Rooting" above.
571 * If you want to add additional methods to Handle for a specific
572 * specialization, define a HandleBase<T> specialization containing them.
574 template <typename T>
575 class MOZ_NONHEAP_CLASS Handle : public js::HandleBase<T, Handle<T>> {
576 friend class MutableHandle<T>;
578 public:
579 using ElementType = T;
581 Handle(const Handle<T>&) = default;
583 /* Creates a handle from a handle of a type convertible to T. */
584 template <typename S>
585 MOZ_IMPLICIT Handle(
586 Handle<S> handle,
587 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0) {
588 static_assert(sizeof(Handle<T>) == sizeof(T*),
589 "Handle must be binary compatible with T*.");
590 ptr = reinterpret_cast<const T*>(handle.address());
593 MOZ_IMPLICIT Handle(decltype(nullptr)) {
594 static_assert(std::is_pointer_v<T>,
595 "nullptr_t overload not valid for non-pointer types");
596 static void* const ConstNullValue = nullptr;
597 ptr = reinterpret_cast<const T*>(&ConstNullValue);
600 MOZ_IMPLICIT Handle(MutableHandle<T> handle) { ptr = handle.address(); }
603 * Take care when calling this method!
605 * This creates a Handle from the raw location of a T.
607 * It should be called only if the following conditions hold:
609 * 1) the location of the T is guaranteed to be marked (for some reason
610 * other than being a Rooted), e.g., if it is guaranteed to be reachable
611 * from an implicit root.
613 * 2) the contents of the location are immutable, or at least cannot change
614 * for the lifetime of the handle, as its users may not expect its value
615 * to change underneath them.
617 static constexpr Handle fromMarkedLocation(const T* p) {
618 return Handle(p, DeliberatelyChoosingThisOverload,
619 ImUsingThisOnlyInFromFromMarkedLocation);
623 * Construct a handle from an explicitly rooted location. This is the
624 * normal way to create a handle, and normally happens implicitly.
626 template <typename S>
627 inline MOZ_IMPLICIT Handle(
628 const Rooted<S>& root,
629 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
631 template <typename S>
632 inline MOZ_IMPLICIT Handle(
633 const PersistentRooted<S>& root,
634 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
636 /* Construct a read only handle from a mutable handle. */
637 template <typename S>
638 inline MOZ_IMPLICIT Handle(
639 MutableHandle<S>& root,
640 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
642 DECLARE_POINTER_CONSTREF_OPS(T);
643 DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr);
645 private:
646 Handle() = default;
647 DELETE_ASSIGNMENT_OPS(Handle, T);
649 enum Disambiguator { DeliberatelyChoosingThisOverload = 42 };
650 enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 };
651 constexpr Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {}
653 const T* ptr;
656 namespace detail {
658 template <typename T>
659 struct DefineComparisonOps<Handle<T>> : std::true_type {
660 static const T& get(const Handle<T>& v) { return v.get(); }
663 } // namespace detail
666 * Similar to a handle, but the underlying storage can be changed. This is
667 * useful for outparams.
669 * If you want to add additional methods to MutableHandle for a specific
670 * specialization, define a MutableHandleBase<T> specialization containing
671 * them.
673 template <typename T>
674 class MOZ_STACK_CLASS MutableHandle
675 : public js::MutableHandleBase<T, MutableHandle<T>> {
676 public:
677 using ElementType = T;
679 inline MOZ_IMPLICIT MutableHandle(Rooted<T>* root);
680 inline MOZ_IMPLICIT MutableHandle(PersistentRooted<T>* root);
682 private:
683 // Disallow nullptr for overloading purposes.
684 MutableHandle(decltype(nullptr)) = delete;
686 public:
687 MutableHandle(const MutableHandle<T>&) = default;
688 void set(const T& v) {
689 *ptr = v;
690 MOZ_ASSERT(GCPolicy<T>::isValid(*ptr));
692 void set(T&& v) {
693 *ptr = std::move(v);
694 MOZ_ASSERT(GCPolicy<T>::isValid(*ptr));
698 * This may be called only if the location of the T is guaranteed
699 * to be marked (for some reason other than being a Rooted),
700 * e.g., if it is guaranteed to be reachable from an implicit root.
702 * Create a MutableHandle from a raw location of a T.
704 static MutableHandle fromMarkedLocation(T* p) {
705 MutableHandle h;
706 h.ptr = p;
707 return h;
710 DECLARE_POINTER_CONSTREF_OPS(T);
711 DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr);
712 DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr);
714 private:
715 MutableHandle() = default;
716 DELETE_ASSIGNMENT_OPS(MutableHandle, T);
718 T* ptr;
721 namespace detail {
723 template <typename T>
724 struct DefineComparisonOps<MutableHandle<T>> : std::true_type {
725 static const T& get(const MutableHandle<T>& v) { return v.get(); }
728 } // namespace detail
730 } /* namespace JS */
732 namespace js {
734 namespace detail {
736 // Default implementations for barrier methods on GC thing pointers.
737 template <typename T>
738 struct PtrBarrierMethodsBase {
739 static T* initial() { return nullptr; }
740 static gc::Cell* asGCThingOrNull(T* v) {
741 if (!v) {
742 return nullptr;
744 MOZ_ASSERT(uintptr_t(v) > 32);
745 return reinterpret_cast<gc::Cell*>(v);
747 static void exposeToJS(T* t) {
748 if (t) {
749 js::gc::ExposeGCThingToActiveJS(JS::GCCellPtr(t));
754 } // namespace detail
756 template <typename T>
757 struct BarrierMethods<T*> : public detail::PtrBarrierMethodsBase<T> {
758 static void postWriteBarrier(T** vp, T* prev, T* next) {
759 if (next) {
760 JS::AssertGCThingIsNotNurseryAllocable(
761 reinterpret_cast<js::gc::Cell*>(next));
766 template <>
767 struct BarrierMethods<JSObject*>
768 : public detail::PtrBarrierMethodsBase<JSObject> {
769 static void postWriteBarrier(JSObject** vp, JSObject* prev, JSObject* next) {
770 JS::HeapObjectPostWriteBarrier(vp, prev, next);
772 static void exposeToJS(JSObject* obj) {
773 if (obj) {
774 JS::ExposeObjectToActiveJS(obj);
779 template <>
780 struct BarrierMethods<JSFunction*>
781 : public detail::PtrBarrierMethodsBase<JSFunction> {
782 static void postWriteBarrier(JSFunction** vp, JSFunction* prev,
783 JSFunction* next) {
784 JS::HeapObjectPostWriteBarrier(reinterpret_cast<JSObject**>(vp),
785 reinterpret_cast<JSObject*>(prev),
786 reinterpret_cast<JSObject*>(next));
788 static void exposeToJS(JSFunction* fun) {
789 if (fun) {
790 JS::ExposeObjectToActiveJS(reinterpret_cast<JSObject*>(fun));
795 template <>
796 struct BarrierMethods<JSString*>
797 : public detail::PtrBarrierMethodsBase<JSString> {
798 static void postWriteBarrier(JSString** vp, JSString* prev, JSString* next) {
799 JS::HeapStringPostWriteBarrier(vp, prev, next);
803 template <>
804 struct BarrierMethods<JS::BigInt*>
805 : public detail::PtrBarrierMethodsBase<JS::BigInt> {
806 static void postWriteBarrier(JS::BigInt** vp, JS::BigInt* prev,
807 JS::BigInt* next) {
808 JS::HeapBigIntPostWriteBarrier(vp, prev, next);
812 // Provide hash codes for Cell kinds that may be relocated and, thus, not have
813 // a stable address to use as the base for a hash code. Instead of the address,
814 // this hasher uses Cell::getUniqueId to provide exact matches and as a base
815 // for generating hash codes.
817 // Note: this hasher, like PointerHasher can "hash" a nullptr. While a nullptr
818 // would not likely be a useful key, there are some cases where being able to
819 // hash a nullptr is useful, either on purpose or because of bugs:
820 // (1) existence checks where the key may happen to be null and (2) some
821 // aggregate Lookup kinds embed a JSObject* that is frequently null and do not
822 // null test before dispatching to the hasher.
823 template <typename T>
824 struct JS_PUBLIC_API MovableCellHasher {
825 using Key = T;
826 using Lookup = T;
828 static bool hasHash(const Lookup& l);
829 static bool ensureHash(const Lookup& l);
830 static HashNumber hash(const Lookup& l);
831 static bool match(const Key& k, const Lookup& l);
832 // The rekey hash policy method is not provided since you dont't need to
833 // rekey any more when using this policy.
836 template <typename T>
837 struct JS_PUBLIC_API MovableCellHasher<JS::Heap<T>> {
838 using Key = JS::Heap<T>;
839 using Lookup = T;
841 static bool hasHash(const Lookup& l) {
842 return MovableCellHasher<T>::hasHash(l);
844 static bool ensureHash(const Lookup& l) {
845 return MovableCellHasher<T>::ensureHash(l);
847 static HashNumber hash(const Lookup& l) {
848 return MovableCellHasher<T>::hash(l);
850 static bool match(const Key& k, const Lookup& l) {
851 return MovableCellHasher<T>::match(k.unbarrieredGet(), l);
855 } // namespace js
857 namespace mozilla {
859 template <typename T>
860 struct FallibleHashMethods<js::MovableCellHasher<T>> {
861 template <typename Lookup>
862 static bool hasHash(Lookup&& l) {
863 return js::MovableCellHasher<T>::hasHash(std::forward<Lookup>(l));
865 template <typename Lookup>
866 static bool ensureHash(Lookup&& l) {
867 return js::MovableCellHasher<T>::ensureHash(std::forward<Lookup>(l));
871 } // namespace mozilla
873 namespace js {
875 struct VirtualTraceable {
876 virtual ~VirtualTraceable() = default;
877 virtual void trace(JSTracer* trc, const char* name) = 0;
880 template <typename T>
881 struct RootedTraceable final : public VirtualTraceable {
882 static_assert(JS::MapTypeToRootKind<T>::kind == JS::RootKind::Traceable,
883 "RootedTraceable is intended only for usage with a Traceable");
885 T ptr;
887 template <typename U>
888 MOZ_IMPLICIT RootedTraceable(U&& initial) : ptr(std::forward<U>(initial)) {}
890 operator T&() { return ptr; }
891 operator const T&() const { return ptr; }
893 void trace(JSTracer* trc, const char* name) override {
894 JS::GCPolicy<T>::trace(trc, &ptr, name);
898 template <typename T>
899 struct RootedTraceableTraits {
900 static T* address(RootedTraceable<T>& self) { return &self.ptr; }
901 static const T* address(const RootedTraceable<T>& self) { return &self.ptr; }
902 static void trace(JSTracer* trc, VirtualTraceable* thingp, const char* name);
905 template <typename T>
906 struct RootedGCThingTraits {
907 static T* address(T& self) { return &self; }
908 static const T* address(const T& self) { return &self; }
909 static void trace(JSTracer* trc, T* thingp, const char* name);
912 } /* namespace js */
914 namespace JS {
916 class JS_PUBLIC_API AutoGCRooter;
918 enum class AutoGCRooterKind : uint8_t {
919 WrapperVector, /* js::AutoWrapperVector */
920 Wrapper, /* js::AutoWrapperRooter */
921 Custom, /* js::CustomAutoRooter */
923 Limit
926 namespace detail {
927 // Dummy type to store root list entry pointers as. This code does not just use
928 // the actual type, because then eg JSObject* and JSFunction* would be assumed
929 // to never alias but they do (they are stored in the same list). Also, do not
930 // use `void*` so that `Rooted<void*>` is a compile error.
931 struct RootListEntry;
932 } // namespace detail
934 template <>
935 struct MapTypeToRootKind<detail::RootListEntry*> {
936 static const RootKind kind = RootKind::Traceable;
939 // Workaround MSVC issue where GCPolicy is needed even though this dummy type is
940 // never instantiated. Ideally, RootListEntry is removed in the future and an
941 // appropriate class hierarchy for the Rooted<T> types.
942 template <>
943 struct GCPolicy<detail::RootListEntry*>
944 : public IgnoreGCPolicy<detail::RootListEntry*> {};
946 using RootedListHeads =
947 mozilla::EnumeratedArray<RootKind, RootKind::Limit,
948 Rooted<detail::RootListEntry*>*>;
950 using AutoRooterListHeads =
951 mozilla::EnumeratedArray<AutoGCRooterKind, AutoGCRooterKind::Limit,
952 AutoGCRooter*>;
954 // Superclass of JSContext which can be used for rooting data in use by the
955 // current thread but that does not provide all the functions of a JSContext.
956 class RootingContext {
957 // Stack GC roots for Rooted GC heap pointers.
958 RootedListHeads stackRoots_;
959 template <typename T>
960 friend class Rooted;
962 // Stack GC roots for AutoFooRooter classes.
963 AutoRooterListHeads autoGCRooters_;
964 friend class AutoGCRooter;
966 // Gecko profiling metadata.
967 // This isn't really rooting related. It's only here because we want
968 // GetContextProfilingStackIfEnabled to be inlineable into non-JS code, and
969 // we didn't want to add another superclass of JSContext just for this.
970 js::GeckoProfilerThread geckoProfiler_;
972 public:
973 RootingContext();
975 void traceStackRoots(JSTracer* trc);
977 /* Implemented in gc/RootMarking.cpp. */
978 void traceAllGCRooters(JSTracer* trc);
979 void traceWrapperGCRooters(JSTracer* trc);
980 static void traceGCRooterList(JSTracer* trc, AutoGCRooter* head);
982 void checkNoGCRooters();
984 js::GeckoProfilerThread& geckoProfiler() { return geckoProfiler_; }
986 protected:
987 // The remaining members in this class should only be accessed through
988 // JSContext pointers. They are unrelated to rooting and are in place so
989 // that inlined API functions can directly access the data.
991 /* The current realm. */
992 Realm* realm_;
994 /* The current zone. */
995 Zone* zone_;
997 public:
998 /* Limit pointer for checking native stack consumption. */
999 uintptr_t nativeStackLimit[StackKindCount];
1001 #ifdef __wasi__
1002 // For WASI we can't catch call-stack overflows with stack-pointer checks, so
1003 // we count recursion depth with RAII based AutoCheckRecursionLimit.
1004 uint32_t wasiRecursionDepth = 0u;
1006 static constexpr uint32_t wasiRecursionDepthLimit = 100u;
1007 #endif // __wasi__
1009 static const RootingContext* get(const JSContext* cx) {
1010 return reinterpret_cast<const RootingContext*>(cx);
1013 static RootingContext* get(JSContext* cx) {
1014 return reinterpret_cast<RootingContext*>(cx);
1017 friend JS::Realm* js::GetContextRealm(const JSContext* cx);
1018 friend JS::Zone* js::GetContextZone(const JSContext* cx);
1021 class JS_PUBLIC_API AutoGCRooter {
1022 public:
1023 using Kind = AutoGCRooterKind;
1025 AutoGCRooter(JSContext* cx, Kind kind)
1026 : AutoGCRooter(JS::RootingContext::get(cx), kind) {}
1027 AutoGCRooter(RootingContext* cx, Kind kind)
1028 : down(cx->autoGCRooters_[kind]),
1029 stackTop(&cx->autoGCRooters_[kind]),
1030 kind_(kind) {
1031 MOZ_ASSERT(this != *stackTop);
1032 *stackTop = this;
1035 ~AutoGCRooter() {
1036 MOZ_ASSERT(this == *stackTop);
1037 *stackTop = down;
1040 void trace(JSTracer* trc);
1042 private:
1043 friend class RootingContext;
1045 AutoGCRooter* const down;
1046 AutoGCRooter** const stackTop;
1049 * Discriminates actual subclass of this being used. The meaning is
1050 * indicated by the corresponding value in the Kind enum.
1052 Kind kind_;
1054 /* No copy or assignment semantics. */
1055 AutoGCRooter(AutoGCRooter& ida) = delete;
1056 void operator=(AutoGCRooter& ida) = delete;
1057 } JS_HAZ_ROOTED_BASE;
1060 * Custom rooting behavior for internal and external clients.
1062 * Deprecated. Where possible, use Rooted<> instead.
1064 class MOZ_RAII JS_PUBLIC_API CustomAutoRooter : private AutoGCRooter {
1065 public:
1066 template <typename CX>
1067 explicit CustomAutoRooter(const CX& cx)
1068 : AutoGCRooter(cx, AutoGCRooter::Kind::Custom) {}
1070 friend void AutoGCRooter::trace(JSTracer* trc);
1072 protected:
1073 virtual ~CustomAutoRooter() = default;
1075 /** Supplied by derived class to trace roots. */
1076 virtual void trace(JSTracer* trc) = 0;
1079 namespace detail {
1081 template <typename T>
1082 using RootedPtr =
1083 std::conditional_t<MapTypeToRootKind<T>::kind == JS::RootKind::Traceable,
1084 js::RootedTraceable<T>, T>;
1086 template <typename T>
1087 using RootedPtrTraits =
1088 std::conditional_t<MapTypeToRootKind<T>::kind == JS::RootKind::Traceable,
1089 js::RootedTraceableTraits<T>,
1090 js::RootedGCThingTraits<T>>;
1092 // Dummy types to make it easier to understand template overload preference
1093 // ordering.
1094 struct FallbackOverload {};
1095 struct PreferredOverload : FallbackOverload {};
1096 using OverloadSelector = PreferredOverload;
1098 } /* namespace detail */
1101 * Local variable of type T whose value is always rooted. This is typically
1102 * used for local variables, or for non-rooted values being passed to a
1103 * function that requires a handle, e.g. Foo(Root<T>(cx, x)).
1105 * If you want to add additional methods to Rooted for a specific
1106 * specialization, define a RootedBase<T> specialization containing them.
1108 template <typename T>
1109 class MOZ_RAII Rooted : public js::RootedBase<T, Rooted<T>> {
1110 using Ptr = detail::RootedPtr<T>;
1111 using PtrTraits = detail::RootedPtrTraits<T>;
1113 inline void registerWithRootLists(RootedListHeads& roots) {
1114 this->stack = &roots[JS::MapTypeToRootKind<T>::kind];
1115 this->prev = *stack;
1116 *stack = reinterpret_cast<Rooted<detail::RootListEntry*>*>(this);
1119 inline RootedListHeads& rootLists(RootingContext* cx) {
1120 return cx->stackRoots_;
1122 inline RootedListHeads& rootLists(JSContext* cx) {
1123 return rootLists(RootingContext::get(cx));
1126 // Define either one or two Rooted(cx) constructors: the fallback one, which
1127 // constructs a Rooted holding a SafelyInitialized<T>, and a convenience one
1128 // for types that can be constructed with a cx, which will give a Rooted
1129 // holding a T(cx).
1131 // Dummy type to distinguish these constructors from Rooted(cx, initial)
1132 struct CtorDispatcher {};
1134 // Normal case: construct an empty Rooted holding a safely initialized but
1135 // empty T.
1136 template <typename RootingContext>
1137 Rooted(const RootingContext& cx, CtorDispatcher, detail::FallbackOverload)
1138 : Rooted(cx, SafelyInitialized<T>()) {}
1140 // If T can be constructed with a cx, then define another constructor for it
1141 // that will be preferred.
1142 template <
1143 typename RootingContext,
1144 typename = std::enable_if_t<std::is_constructible_v<T, RootingContext>>>
1145 Rooted(const RootingContext& cx, CtorDispatcher, detail::PreferredOverload)
1146 : Rooted(cx, T(cx)) {}
1148 public:
1149 using ElementType = T;
1151 // Construct an empty Rooted. Delegates to an internal constructor that
1152 // chooses a specific meaning of "empty" depending on whether T can be
1153 // constructed with a cx.
1154 template <typename RootingContext>
1155 explicit Rooted(const RootingContext& cx)
1156 : Rooted(cx, CtorDispatcher(), detail::OverloadSelector()) {}
1158 template <typename RootingContext, typename S>
1159 Rooted(const RootingContext& cx, S&& initial)
1160 : ptr(std::forward<S>(initial)) {
1161 MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1162 registerWithRootLists(rootLists(cx));
1165 ~Rooted() {
1166 MOZ_ASSERT(*stack ==
1167 reinterpret_cast<Rooted<detail::RootListEntry*>*>(this));
1168 *stack = prev;
1171 Rooted<T>* previous() { return reinterpret_cast<Rooted<T>*>(prev); }
1174 * This method is public for Rooted so that Codegen.py can use a Rooted
1175 * interchangeably with a MutableHandleValue.
1177 void set(const T& value) {
1178 ptr = value;
1179 MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1181 void set(T&& value) {
1182 ptr = std::move(value);
1183 MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1186 DECLARE_POINTER_CONSTREF_OPS(T);
1187 DECLARE_POINTER_ASSIGN_OPS(Rooted, T);
1189 T& get() { return ptr; }
1190 const T& get() const { return ptr; }
1192 T* address() { return PtrTraits::address(ptr); }
1193 const T* address() const { return PtrTraits::address(ptr); }
1195 void trace(JSTracer* trc, const char* name);
1197 private:
1199 * These need to be templated on RootListEntry* to avoid aliasing issues
1200 * between, for example, Rooted<JSObject*> and Rooted<JSFunction*>, which use
1201 * the same stack head pointer for different classes.
1203 Rooted<detail::RootListEntry*>** stack;
1204 Rooted<detail::RootListEntry*>* prev;
1206 Ptr ptr;
1208 Rooted(const Rooted&) = delete;
1209 } JS_HAZ_ROOTED;
1211 namespace detail {
1213 template <typename T>
1214 struct DefineComparisonOps<Rooted<T>> : std::true_type {
1215 static const T& get(const Rooted<T>& v) { return v.get(); }
1218 } // namespace detail
1220 } /* namespace JS */
1222 namespace js {
1225 * Inlinable accessors for JSContext.
1227 * - These must not be available on the more restricted superclasses of
1228 * JSContext, so we can't simply define them on RootingContext.
1230 * - They're perfectly ordinary JSContext functionality, so ought to be
1231 * usable without resorting to jsfriendapi.h, and when JSContext is an
1232 * incomplete type.
1234 inline JS::Realm* GetContextRealm(const JSContext* cx) {
1235 return JS::RootingContext::get(cx)->realm_;
1238 inline JS::Compartment* GetContextCompartment(const JSContext* cx) {
1239 if (JS::Realm* realm = GetContextRealm(cx)) {
1240 return GetCompartmentForRealm(realm);
1242 return nullptr;
1245 inline JS::Zone* GetContextZone(const JSContext* cx) {
1246 return JS::RootingContext::get(cx)->zone_;
1249 inline ProfilingStack* GetContextProfilingStackIfEnabled(JSContext* cx) {
1250 return JS::RootingContext::get(cx)
1251 ->geckoProfiler()
1252 .getProfilingStackIfEnabled();
1256 * Augment the generic Rooted<T> interface when T = JSObject* with
1257 * class-querying and downcasting operations.
1259 * Given a Rooted<JSObject*> obj, one can view
1260 * Handle<StringObject*> h = obj.as<StringObject*>();
1261 * as an optimization of
1262 * Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
1263 * Handle<StringObject*> h = rooted;
1265 template <typename Container>
1266 class RootedBase<JSObject*, Container>
1267 : public MutableWrappedPtrOperations<JSObject*, Container> {
1268 public:
1269 template <class U>
1270 JS::Handle<U*> as() const;
1274 * Augment the generic Handle<T> interface when T = JSObject* with
1275 * downcasting operations.
1277 * Given a Handle<JSObject*> obj, one can view
1278 * Handle<StringObject*> h = obj.as<StringObject*>();
1279 * as an optimization of
1280 * Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
1281 * Handle<StringObject*> h = rooted;
1283 template <typename Container>
1284 class HandleBase<JSObject*, Container>
1285 : public WrappedPtrOperations<JSObject*, Container> {
1286 public:
1287 template <class U>
1288 JS::Handle<U*> as() const;
1291 } /* namespace js */
1293 namespace JS {
1295 template <typename T>
1296 template <typename S>
1297 inline Handle<T>::Handle(
1298 const Rooted<S>& root,
1299 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1300 ptr = reinterpret_cast<const T*>(root.address());
1303 template <typename T>
1304 template <typename S>
1305 inline Handle<T>::Handle(
1306 const PersistentRooted<S>& root,
1307 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1308 ptr = reinterpret_cast<const T*>(root.address());
1311 template <typename T>
1312 template <typename S>
1313 inline Handle<T>::Handle(
1314 MutableHandle<S>& root,
1315 std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1316 ptr = reinterpret_cast<const T*>(root.address());
1319 template <typename T>
1320 inline MutableHandle<T>::MutableHandle(Rooted<T>* root) {
1321 static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1322 "MutableHandle must be binary compatible with T*.");
1323 ptr = root->address();
1326 template <typename T>
1327 inline MutableHandle<T>::MutableHandle(PersistentRooted<T>* root) {
1328 static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1329 "MutableHandle must be binary compatible with T*.");
1330 ptr = root->address();
1333 JS_PUBLIC_API void AddPersistentRoot(
1334 RootingContext* cx, RootKind kind,
1335 PersistentRooted<detail::RootListEntry*>* root);
1337 JS_PUBLIC_API void AddPersistentRoot(
1338 JSRuntime* rt, RootKind kind,
1339 PersistentRooted<detail::RootListEntry*>* root);
1342 * A copyable, assignable global GC root type with arbitrary lifetime, an
1343 * infallible constructor, and automatic unrooting on destruction.
1345 * These roots can be used in heap-allocated data structures, so they are not
1346 * associated with any particular JSContext or stack. They are registered with
1347 * the JSRuntime itself, without locking. Initialization may take place on
1348 * construction, or in two phases if the no-argument constructor is called
1349 * followed by init().
1351 * Note that you must not use an PersistentRooted in an object owned by a JS
1352 * object:
1354 * Whenever one object whose lifetime is decided by the GC refers to another
1355 * such object, that edge must be traced only if the owning JS object is traced.
1356 * This applies not only to JS objects (which obviously are managed by the GC)
1357 * but also to C++ objects owned by JS objects.
1359 * If you put a PersistentRooted in such a C++ object, that is almost certainly
1360 * a leak. When a GC begins, the referent of the PersistentRooted is treated as
1361 * live, unconditionally (because a PersistentRooted is a *root*), even if the
1362 * JS object that owns it is unreachable. If there is any path from that
1363 * referent back to the JS object, then the C++ object containing the
1364 * PersistentRooted will not be destructed, and the whole blob of objects will
1365 * not be freed, even if there are no references to them from the outside.
1367 * In the context of Firefox, this is a severe restriction: almost everything in
1368 * Firefox is owned by some JS object or another, so using PersistentRooted in
1369 * such objects would introduce leaks. For these kinds of edges, Heap<T> or
1370 * TenuredHeap<T> would be better types. It's up to the implementor of the type
1371 * containing Heap<T> or TenuredHeap<T> members to make sure their referents get
1372 * marked when the object itself is marked.
1374 template <typename T>
1375 class PersistentRooted
1376 : public js::RootedBase<T, PersistentRooted<T>>,
1377 private mozilla::LinkedListElement<PersistentRooted<T>> {
1378 using ListBase = mozilla::LinkedListElement<PersistentRooted<T>>;
1379 using Ptr = detail::RootedPtr<T>;
1380 using PtrTraits = detail::RootedPtrTraits<T>;
1382 friend class mozilla::LinkedList<PersistentRooted>;
1383 friend class mozilla::LinkedListElement<PersistentRooted>;
1385 void registerWithRootLists(RootingContext* cx) {
1386 MOZ_ASSERT(!initialized());
1387 JS::RootKind kind = JS::MapTypeToRootKind<T>::kind;
1388 AddPersistentRoot(
1389 cx, kind,
1390 reinterpret_cast<JS::PersistentRooted<detail::RootListEntry*>*>(this));
1393 void registerWithRootLists(JSRuntime* rt) {
1394 MOZ_ASSERT(!initialized());
1395 JS::RootKind kind = JS::MapTypeToRootKind<T>::kind;
1396 AddPersistentRoot(
1397 rt, kind,
1398 reinterpret_cast<JS::PersistentRooted<detail::RootListEntry*>*>(this));
1401 public:
1402 using ElementType = T;
1404 PersistentRooted() : ptr(SafelyInitialized<T>()) {}
1406 explicit PersistentRooted(RootingContext* cx) : ptr(SafelyInitialized<T>()) {
1407 registerWithRootLists(cx);
1410 explicit PersistentRooted(JSContext* cx) : ptr(SafelyInitialized<T>()) {
1411 registerWithRootLists(RootingContext::get(cx));
1414 template <typename U>
1415 PersistentRooted(RootingContext* cx, U&& initial)
1416 : ptr(std::forward<U>(initial)) {
1417 registerWithRootLists(cx);
1420 template <typename U>
1421 PersistentRooted(JSContext* cx, U&& initial) : ptr(std::forward<U>(initial)) {
1422 registerWithRootLists(RootingContext::get(cx));
1425 explicit PersistentRooted(JSRuntime* rt) : ptr(SafelyInitialized<T>()) {
1426 registerWithRootLists(rt);
1429 template <typename U>
1430 PersistentRooted(JSRuntime* rt, U&& initial) : ptr(std::forward<U>(initial)) {
1431 registerWithRootLists(rt);
1434 PersistentRooted(const PersistentRooted& rhs)
1435 : mozilla::LinkedListElement<PersistentRooted<T>>(), ptr(rhs.ptr) {
1437 * Copy construction takes advantage of the fact that the original
1438 * is already inserted, and simply adds itself to whatever list the
1439 * original was on - no JSRuntime pointer needed.
1441 * This requires mutating rhs's links, but those should be 'mutable'
1442 * anyway. C++ doesn't let us declare mutable base classes.
1444 const_cast<PersistentRooted&>(rhs).setNext(this);
1447 bool initialized() const { return ListBase::isInList(); }
1449 void init(RootingContext* cx) { init(cx, SafelyInitialized<T>()); }
1450 void init(JSContext* cx) { init(RootingContext::get(cx)); }
1452 template <typename U>
1453 void init(RootingContext* cx, U&& initial) {
1454 ptr = std::forward<U>(initial);
1455 registerWithRootLists(cx);
1457 template <typename U>
1458 void init(JSContext* cx, U&& initial) {
1459 ptr = std::forward<U>(initial);
1460 registerWithRootLists(RootingContext::get(cx));
1463 void reset() {
1464 if (initialized()) {
1465 set(SafelyInitialized<T>());
1466 ListBase::remove();
1470 DECLARE_POINTER_CONSTREF_OPS(T);
1471 DECLARE_POINTER_ASSIGN_OPS(PersistentRooted, T);
1473 T& get() { return ptr; }
1474 const T& get() const { return ptr; }
1476 T* address() {
1477 MOZ_ASSERT(initialized());
1478 return PtrTraits::address(ptr);
1480 const T* address() const { return PtrTraits::address(ptr); }
1482 template <typename U>
1483 void set(U&& value) {
1484 MOZ_ASSERT(initialized());
1485 ptr = std::forward<U>(value);
1488 void trace(JSTracer* trc, const char* name);
1490 private:
1491 Ptr ptr;
1492 } JS_HAZ_ROOTED;
1494 namespace detail {
1496 template <typename T>
1497 struct DefineComparisonOps<PersistentRooted<T>> : std::true_type {
1498 static const T& get(const PersistentRooted<T>& v) { return v.get(); }
1501 } // namespace detail
1503 } /* namespace JS */
1505 namespace js {
1507 template <typename T, typename D, typename Container>
1508 class WrappedPtrOperations<UniquePtr<T, D>, Container> {
1509 const UniquePtr<T, D>& uniquePtr() const {
1510 return static_cast<const Container*>(this)->get();
1513 public:
1514 explicit operator bool() const { return !!uniquePtr(); }
1515 T* get() const { return uniquePtr().get(); }
1516 T* operator->() const { return get(); }
1517 T& operator*() const { return *uniquePtr(); }
1520 template <typename T, typename D, typename Container>
1521 class MutableWrappedPtrOperations<UniquePtr<T, D>, Container>
1522 : public WrappedPtrOperations<UniquePtr<T, D>, Container> {
1523 UniquePtr<T, D>& uniquePtr() { return static_cast<Container*>(this)->get(); }
1525 public:
1526 [[nodiscard]] typename UniquePtr<T, D>::Pointer release() {
1527 return uniquePtr().release();
1529 void reset(T* ptr = T()) { uniquePtr().reset(ptr); }
1532 template <typename T, typename Container>
1533 class WrappedPtrOperations<mozilla::Maybe<T>, Container> {
1534 const mozilla::Maybe<T>& maybe() const {
1535 return static_cast<const Container*>(this)->get();
1538 public:
1539 // This only supports a subset of Maybe's interface.
1540 bool isSome() const { return maybe().isSome(); }
1541 bool isNothing() const { return maybe().isNothing(); }
1542 const T value() const { return maybe().value(); }
1543 const T* operator->() const { return maybe().ptr(); }
1544 const T& operator*() const { return maybe().ref(); }
1547 template <typename T, typename Container>
1548 class MutableWrappedPtrOperations<mozilla::Maybe<T>, Container>
1549 : public WrappedPtrOperations<mozilla::Maybe<T>, Container> {
1550 mozilla::Maybe<T>& maybe() { return static_cast<Container*>(this)->get(); }
1552 public:
1553 // This only supports a subset of Maybe's interface.
1554 T* operator->() { return maybe().ptr(); }
1555 T& operator*() { return maybe().ref(); }
1556 void reset() { return maybe().reset(); }
1559 namespace gc {
1561 template <typename T, typename TraceCallbacks>
1562 void CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks,
1563 const char* aName, void* aClosure) {
1564 static_assert(sizeof(T) == sizeof(JS::Heap<T>),
1565 "T and Heap<T> must be compatible.");
1566 MOZ_ASSERT(v);
1567 mozilla::DebugOnly<Cell*> cell = BarrierMethods<T>::asGCThingOrNull(*v);
1568 MOZ_ASSERT(cell);
1569 MOZ_ASSERT(!IsInsideNursery(cell));
1570 JS::Heap<T>* asHeapT = reinterpret_cast<JS::Heap<T>*>(v);
1571 aCallbacks.Trace(asHeapT, aName, aClosure);
1574 } /* namespace gc */
1576 } /* namespace js */
1578 #endif /* js_RootingAPI_h */