Bumping manifests a=b2g-bump
[gecko.git] / js / public / RootingAPI.h
blob1b69bf28e1ce24cd0346fa977f26b9a7f1a8ae0a
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 * vim: set ts=8 sts=4 et sw=4 tw=99:
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/GuardObjects.h"
13 #include "mozilla/LinkedList.h"
14 #include "mozilla/NullPtr.h"
15 #include "mozilla/TypeTraits.h"
17 #include "jspubtd.h"
19 #include "js/GCAPI.h"
20 #include "js/HeapAPI.h"
21 #include "js/TypeDecls.h"
22 #include "js/Utility.h"
25 * Moving GC Stack Rooting
27 * A moving GC may change the physical location of GC allocated things, even
28 * when they are rooted, updating all pointers to the thing to refer to its new
29 * location. The GC must therefore know about all live pointers to a thing,
30 * not just one of them, in order to behave correctly.
32 * The |Rooted| and |Handle| classes below are used to root stack locations
33 * whose value may be held live across a call that can trigger GC. For a
34 * code fragment such as:
36 * JSObject* obj = NewObject(cx);
37 * DoSomething(cx);
38 * ... = obj->lastProperty();
40 * If |DoSomething()| can trigger a GC, the stack location of |obj| must be
41 * rooted to ensure that the GC does not move the JSObject referred to by
42 * |obj| without updating |obj|'s location itself. This rooting must happen
43 * regardless of whether there are other roots which ensure that the object
44 * itself will not be collected.
46 * If |DoSomething()| cannot trigger a GC, and the same holds for all other
47 * calls made between |obj|'s definitions and its last uses, then no rooting
48 * is required.
50 * SpiderMonkey can trigger a GC at almost any time and in ways that are not
51 * always clear. For example, the following innocuous-looking actions can
52 * cause a GC: allocation of any new GC thing; JSObject::hasProperty;
53 * JS_ReportError and friends; and ToNumber, among many others. The following
54 * dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_,
55 * rt->malloc_, and friends and JS_ReportOutOfMemory.
57 * The following family of three classes will exactly root a stack location.
58 * Incorrect usage of these classes will result in a compile error in almost
59 * all cases. Therefore, it is very hard to be incorrectly rooted if you use
60 * these classes exclusively. These classes are all templated on the type T of
61 * the value being rooted.
63 * - Rooted<T> declares a variable of type T, whose value is always rooted.
64 * Rooted<T> may be automatically coerced to a Handle<T>, below. Rooted<T>
65 * should be used whenever a local variable's value may be held live across a
66 * call which can trigger a GC.
68 * - Handle<T> is a const reference to a Rooted<T>. Functions which take GC
69 * things or values as arguments and need to root those arguments should
70 * generally use handles for those arguments and avoid any explicit rooting.
71 * This has two benefits. First, when several such functions call each other
72 * then redundant rooting of multiple copies of the GC thing can be avoided.
73 * Second, if the caller does not pass a rooted value a compile error will be
74 * generated, which is quicker and easier to fix than when relying on a
75 * separate rooting analysis.
77 * - MutableHandle<T> is a non-const reference to Rooted<T>. It is used in the
78 * same way as Handle<T> and includes a |set(const T& v)| method to allow
79 * updating the value of the referenced Rooted<T>. A MutableHandle<T> can be
80 * created from a Rooted<T> by using |Rooted<T>::operator&()|.
82 * In some cases the small performance overhead of exact rooting (measured to
83 * be a few nanoseconds on desktop) is too much. In these cases, try the
84 * following:
86 * - Move all Rooted<T> above inner loops: this allows you to re-use the root
87 * on each iteration of the loop.
89 * - Pass Handle<T> through your hot call stack to avoid re-rooting costs at
90 * every invocation.
92 * The following diagram explains the list of supported, implicit type
93 * conversions between classes of this family:
95 * Rooted<T> ----> Handle<T>
96 * | ^
97 * | |
98 * | |
99 * +---> MutableHandle<T>
100 * (via &)
102 * All of these types have an implicit conversion to raw pointers.
105 namespace js {
107 template <typename T>
108 struct GCMethods {};
110 template <typename T>
111 class RootedBase {};
113 template <typename T>
114 class HandleBase {};
116 template <typename T>
117 class MutableHandleBase {};
119 template <typename T>
120 class HeapBase {};
123 * js::NullPtr acts like a nullptr pointer in contexts that require a Handle.
125 * Handle provides an implicit constructor for js::NullPtr so that, given:
126 * foo(Handle<JSObject*> h);
127 * callers can simply write:
128 * foo(js::NullPtr());
129 * which avoids creating a Rooted<JSObject*> just to pass nullptr.
131 * This is the SpiderMonkey internal variant. js::NullPtr should be used in
132 * preference to JS::NullPtr to avoid the GOT access required for JS_PUBLIC_API
133 * symbols.
135 struct NullPtr
137 static void * const constNullValue;
140 namespace gc {
141 struct Cell;
142 template<typename T>
143 struct PersistentRootedMarker;
144 } /* namespace gc */
146 } /* namespace js */
148 namespace JS {
150 template <typename T> class Rooted;
151 template <typename T> class PersistentRooted;
153 /* This is exposing internal state of the GC for inlining purposes. */
154 JS_FRIEND_API(bool) isGCEnabled();
157 * JS::NullPtr acts like a nullptr pointer in contexts that require a Handle.
159 * Handle provides an implicit constructor for JS::NullPtr so that, given:
160 * foo(Handle<JSObject*> h);
161 * callers can simply write:
162 * foo(JS::NullPtr());
163 * which avoids creating a Rooted<JSObject*> just to pass nullptr.
165 struct JS_PUBLIC_API(NullPtr)
167 static void * const constNullValue;
170 JS_FRIEND_API(void) HeapCellPostBarrier(js::gc::Cell** cellp);
171 JS_FRIEND_API(void) HeapCellRelocate(js::gc::Cell** cellp);
173 #ifdef JS_DEBUG
175 * For generational GC, assert that an object is in the tenured generation as
176 * opposed to being in the nursery.
178 extern JS_FRIEND_API(void)
179 AssertGCThingMustBeTenured(JSObject* obj);
180 #else
181 inline void
182 AssertGCThingMustBeTenured(JSObject* obj) {}
183 #endif
186 * The Heap<T> class is a heap-stored reference to a JS GC thing. All members of
187 * heap classes that refer to GC things should use Heap<T> (or possibly
188 * TenuredHeap<T>, described below).
190 * Heap<T> is an abstraction that hides some of the complexity required to
191 * maintain GC invariants for the contained reference. It uses operator
192 * overloading to provide a normal pointer interface, but notifies the GC every
193 * time the value it contains is updated. This is necessary for generational GC,
194 * which keeps track of all pointers into the nursery.
196 * Heap<T> instances must be traced when their containing object is traced to
197 * keep the pointed-to GC thing alive.
199 * Heap<T> objects should only be used on the heap. GC references stored on the
200 * C/C++ stack must use Rooted/Handle/MutableHandle instead.
202 * Type T must be one of: JS::Value, jsid, JSObject*, JSString*, JSScript*
204 template <typename T>
205 class Heap : public js::HeapBase<T>
207 public:
208 Heap() {
209 static_assert(sizeof(T) == sizeof(Heap<T>),
210 "Heap<T> must be binary compatible with T.");
211 init(js::GCMethods<T>::initial());
213 explicit Heap(T p) { init(p); }
216 * For Heap, move semantics are equivalent to copy semantics. In C++, a
217 * copy constructor taking const-ref is the way to get a single function
218 * that will be used for both lvalue and rvalue copies, so we can simply
219 * omit the rvalue variant.
221 explicit Heap(const Heap<T>& p) { init(p.ptr); }
223 ~Heap() {
224 if (js::GCMethods<T>::needsPostBarrier(ptr))
225 relocate();
228 bool operator==(const Heap<T>& other) { return ptr == other.ptr; }
229 bool operator!=(const Heap<T>& other) { return ptr != other.ptr; }
231 bool operator==(const T& other) const { return ptr == other; }
232 bool operator!=(const T& other) const { return ptr != other; }
234 operator T() const { return ptr; }
235 T operator->() const { return ptr; }
236 const T* address() const { return &ptr; }
237 const T& get() const { return ptr; }
239 T* unsafeGet() { return &ptr; }
241 Heap<T>& operator=(T p) {
242 set(p);
243 return *this;
246 Heap<T>& operator=(const Heap<T>& other) {
247 set(other.get());
248 return *this;
251 void set(T newPtr) {
252 MOZ_ASSERT(!js::GCMethods<T>::poisoned(newPtr));
253 if (js::GCMethods<T>::needsPostBarrier(newPtr)) {
254 ptr = newPtr;
255 post();
256 } else if (js::GCMethods<T>::needsPostBarrier(ptr)) {
257 relocate(); /* Called before overwriting ptr. */
258 ptr = newPtr;
259 } else {
260 ptr = newPtr;
265 * Set the pointer to a value which will cause a crash if it is
266 * dereferenced.
268 void setToCrashOnTouch() {
269 ptr = reinterpret_cast<T>(crashOnTouchPointer);
272 bool isSetToCrashOnTouch() {
273 return ptr == crashOnTouchPointer;
276 private:
277 void init(T newPtr) {
278 MOZ_ASSERT(!js::GCMethods<T>::poisoned(newPtr));
279 ptr = newPtr;
280 if (js::GCMethods<T>::needsPostBarrier(ptr))
281 post();
284 void post() {
285 MOZ_ASSERT(js::GCMethods<T>::needsPostBarrier(ptr));
286 js::GCMethods<T>::postBarrier(&ptr);
289 void relocate() {
290 js::GCMethods<T>::relocate(&ptr);
293 enum {
294 crashOnTouchPointer = 1
297 T ptr;
301 * The TenuredHeap<T> class is similar to the Heap<T> class above in that it
302 * encapsulates the GC concerns of an on-heap reference to a JS object. However,
303 * it has two important differences:
305 * 1) Pointers which are statically known to only reference "tenured" objects
306 * can avoid the extra overhead of SpiderMonkey's write barriers.
308 * 2) Objects in the "tenured" heap have stronger alignment restrictions than
309 * those in the "nursery", so it is possible to store flags in the lower
310 * bits of pointers known to be tenured. TenuredHeap wraps a normal tagged
311 * pointer with a nice API for accessing the flag bits and adds various
312 * assertions to ensure that it is not mis-used.
314 * GC things are said to be "tenured" when they are located in the long-lived
315 * heap: e.g. they have gained tenure as an object by surviving past at least
316 * one GC. For performance, SpiderMonkey allocates some things which are known
317 * to normally be long lived directly into the tenured generation; for example,
318 * global objects. Additionally, SpiderMonkey does not visit individual objects
319 * when deleting non-tenured objects, so object with finalizers are also always
320 * tenured; for instance, this includes most DOM objects.
322 * The considerations to keep in mind when using a TenuredHeap<T> vs a normal
323 * Heap<T> are:
325 * - It is invalid for a TenuredHeap<T> to refer to a non-tenured thing.
326 * - It is however valid for a Heap<T> to refer to a tenured thing.
327 * - It is not possible to store flag bits in a Heap<T>.
329 template <typename T>
330 class TenuredHeap : public js::HeapBase<T>
332 public:
333 TenuredHeap() : bits(0) {
334 static_assert(sizeof(T) == sizeof(TenuredHeap<T>),
335 "TenuredHeap<T> must be binary compatible with T.");
337 explicit TenuredHeap(T p) : bits(0) { setPtr(p); }
338 explicit TenuredHeap(const TenuredHeap<T>& p) : bits(0) { setPtr(p.getPtr()); }
340 bool operator==(const TenuredHeap<T>& other) { return bits == other.bits; }
341 bool operator!=(const TenuredHeap<T>& other) { return bits != other.bits; }
343 void setPtr(T newPtr) {
344 MOZ_ASSERT((reinterpret_cast<uintptr_t>(newPtr) & flagsMask) == 0);
345 MOZ_ASSERT(!js::GCMethods<T>::poisoned(newPtr));
346 if (newPtr)
347 AssertGCThingMustBeTenured(newPtr);
348 bits = (bits & flagsMask) | reinterpret_cast<uintptr_t>(newPtr);
351 void setFlags(uintptr_t flagsToSet) {
352 MOZ_ASSERT((flagsToSet & ~flagsMask) == 0);
353 bits |= flagsToSet;
356 void unsetFlags(uintptr_t flagsToUnset) {
357 MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0);
358 bits &= ~flagsToUnset;
361 bool hasFlag(uintptr_t flag) const {
362 MOZ_ASSERT((flag & ~flagsMask) == 0);
363 return (bits & flag) != 0;
366 T getPtr() const { return reinterpret_cast<T>(bits & ~flagsMask); }
367 uintptr_t getFlags() const { return bits & flagsMask; }
369 operator T() const { return getPtr(); }
370 T operator->() const { return getPtr(); }
372 TenuredHeap<T>& operator=(T p) {
373 setPtr(p);
374 return *this;
377 TenuredHeap<T>& operator=(const TenuredHeap<T>& other) {
378 bits = other.bits;
379 return *this;
382 private:
383 enum {
384 maskBits = 3,
385 flagsMask = (1 << maskBits) - 1,
388 uintptr_t bits;
392 * Reference to a T that has been rooted elsewhere. This is most useful
393 * as a parameter type, which guarantees that the T lvalue is properly
394 * rooted. See "Move GC Stack Rooting" above.
396 * If you want to add additional methods to Handle for a specific
397 * specialization, define a HandleBase<T> specialization containing them.
399 template <typename T>
400 class MOZ_NONHEAP_CLASS Handle : public js::HandleBase<T>
402 friend class JS::MutableHandle<T>;
404 public:
405 /* Creates a handle from a handle of a type convertible to T. */
406 template <typename S>
407 Handle(Handle<S> handle,
408 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy = 0)
410 static_assert(sizeof(Handle<T>) == sizeof(T*),
411 "Handle must be binary compatible with T*.");
412 ptr = reinterpret_cast<const T*>(handle.address());
415 /* Create a handle for a nullptr pointer. */
416 MOZ_IMPLICIT Handle(js::NullPtr) {
417 static_assert(mozilla::IsPointer<T>::value,
418 "js::NullPtr overload not valid for non-pointer types");
419 ptr = reinterpret_cast<const T*>(&js::NullPtr::constNullValue);
422 /* Create a handle for a nullptr pointer. */
423 MOZ_IMPLICIT Handle(JS::NullPtr) {
424 static_assert(mozilla::IsPointer<T>::value,
425 "JS::NullPtr overload not valid for non-pointer types");
426 ptr = reinterpret_cast<const T*>(&JS::NullPtr::constNullValue);
429 MOZ_IMPLICIT Handle(MutableHandle<T> handle) {
430 ptr = handle.address();
434 * Take care when calling this method!
436 * This creates a Handle from the raw location of a T.
438 * It should be called only if the following conditions hold:
440 * 1) the location of the T is guaranteed to be marked (for some reason
441 * other than being a Rooted), e.g., if it is guaranteed to be reachable
442 * from an implicit root.
444 * 2) the contents of the location are immutable, or at least cannot change
445 * for the lifetime of the handle, as its users may not expect its value
446 * to change underneath them.
448 static MOZ_CONSTEXPR Handle fromMarkedLocation(const T* p) {
449 return Handle(p, DeliberatelyChoosingThisOverload,
450 ImUsingThisOnlyInFromFromMarkedLocation);
454 * Construct a handle from an explicitly rooted location. This is the
455 * normal way to create a handle, and normally happens implicitly.
457 template <typename S>
458 inline
459 Handle(const Rooted<S>& root,
460 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy = 0);
462 template <typename S>
463 inline
464 Handle(const PersistentRooted<S>& root,
465 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy = 0);
467 /* Construct a read only handle from a mutable handle. */
468 template <typename S>
469 inline
470 Handle(MutableHandle<S>& root,
471 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy = 0);
473 const T* address() const { return ptr; }
474 const T& get() const { return *ptr; }
477 * Return a reference so passing a Handle<T> to something that
478 * takes a |const T&| is not a GC hazard.
480 operator const T&() const { return get(); }
481 T operator->() const { return get(); }
483 bool operator!=(const T& other) const { return *ptr != other; }
484 bool operator==(const T& other) const { return *ptr == other; }
486 private:
487 Handle() {}
489 enum Disambiguator { DeliberatelyChoosingThisOverload = 42 };
490 enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 };
491 MOZ_CONSTEXPR Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {}
493 const T* ptr;
495 template <typename S> void operator=(S) = delete;
496 void operator=(Handle) = delete;
500 * Similar to a handle, but the underlying storage can be changed. This is
501 * useful for outparams.
503 * If you want to add additional methods to MutableHandle for a specific
504 * specialization, define a MutableHandleBase<T> specialization containing
505 * them.
507 template <typename T>
508 class MOZ_STACK_CLASS MutableHandle : public js::MutableHandleBase<T>
510 public:
511 inline MOZ_IMPLICIT MutableHandle(Rooted<T>* root);
512 inline MOZ_IMPLICIT MutableHandle(PersistentRooted<T>* root);
514 private:
515 // Disallow true nullptr and emulated nullptr (gcc 4.4/4.5, __null, appears
516 // as int/long [32/64-bit]) for overloading purposes.
517 template<typename N>
518 MutableHandle(N,
519 typename mozilla::EnableIf<mozilla::IsNullPointer<N>::value ||
520 mozilla::IsSame<N, int>::value ||
521 mozilla::IsSame<N, long>::value,
522 int>::Type dummy = 0)
523 = delete;
525 public:
526 void set(T v) {
527 MOZ_ASSERT(!js::GCMethods<T>::poisoned(v));
528 *ptr = v;
532 * This may be called only if the location of the T is guaranteed
533 * to be marked (for some reason other than being a Rooted),
534 * e.g., if it is guaranteed to be reachable from an implicit root.
536 * Create a MutableHandle from a raw location of a T.
538 static MutableHandle fromMarkedLocation(T* p) {
539 MutableHandle h;
540 h.ptr = p;
541 return h;
544 T* address() const { return ptr; }
545 const T& get() const { return *ptr; }
548 * Return a reference so passing a MutableHandle<T> to something that takes
549 * a |const T&| is not a GC hazard.
551 operator const T&() const { return get(); }
552 T operator->() const { return get(); }
554 private:
555 MutableHandle() {}
557 T* ptr;
559 template <typename S> void operator=(S v) = delete;
560 void operator=(MutableHandle other) = delete;
563 } /* namespace JS */
565 namespace js {
568 * InternalHandle is a handle to an internal pointer into a gcthing. Use
569 * InternalHandle when you have a pointer to a direct field of a gcthing, or
570 * when you need a parameter type for something that *may* be a pointer to a
571 * direct field of a gcthing.
573 template <typename T>
574 class InternalHandle {};
576 template <typename T>
577 class InternalHandle<T*>
579 void * const* holder;
580 size_t offset;
582 public:
584 * Create an InternalHandle using a Handle to the gcthing containing the
585 * field in question, and a pointer to the field.
587 template<typename H>
588 InternalHandle(const JS::Handle<H>& handle, T* field)
589 : holder((void**)handle.address()), offset(uintptr_t(field) - uintptr_t(handle.get()))
593 * Create an InternalHandle to a field within a Rooted<>.
595 template<typename R>
596 InternalHandle(const JS::Rooted<R>& root, T* field)
597 : holder((void**)root.address()), offset(uintptr_t(field) - uintptr_t(root.get()))
600 InternalHandle(const InternalHandle<T*>& other)
601 : holder(other.holder), offset(other.offset) {}
603 T* get() const { return reinterpret_cast<T*>(uintptr_t(*holder) + offset); }
605 const T& operator*() const { return *get(); }
606 T* operator->() const { return get(); }
608 static InternalHandle<T*> fromMarkedLocation(T* fieldPtr) {
609 return InternalHandle(fieldPtr);
612 private:
614 * Create an InternalHandle to something that is not a pointer to a
615 * gcthing, and so does not need to be rooted in the first place. Use these
616 * InternalHandles to pass pointers into functions that also need to accept
617 * regular InternalHandles to gcthing fields.
619 * Make this private to prevent accidental misuse; this is only for
620 * fromMarkedLocation().
622 explicit InternalHandle(T* field)
623 : holder(reinterpret_cast<void * const*>(&js::NullPtr::constNullValue)),
624 offset(uintptr_t(field))
627 void operator=(InternalHandle<T*> other) = delete;
631 * By default, things should use the inheritance hierarchy to find their
632 * ThingRootKind. Some pointer types are explicitly set in jspubtd.h so that
633 * Rooted<T> may be used without the class definition being available.
635 template <typename T>
636 struct RootKind
638 static ThingRootKind rootKind() { return T::rootKind(); }
641 template <typename T>
642 struct RootKind<T*>
644 static ThingRootKind rootKind() { return T::rootKind(); }
647 template <typename T>
648 struct GCMethods<T*>
650 static T* initial() { return nullptr; }
651 static bool poisoned(T* v) { return JS::IsPoisonedPtr(v); }
652 static bool needsPostBarrier(T* v) { return false; }
653 static void postBarrier(T** vp) {}
654 static void relocate(T** vp) {}
657 template <>
658 struct GCMethods<JSObject*>
660 static JSObject* initial() { return nullptr; }
661 static bool poisoned(JSObject* v) { return JS::IsPoisonedPtr(v); }
662 static gc::Cell* asGCThingOrNull(JSObject* v) {
663 if (!v)
664 return nullptr;
665 MOZ_ASSERT(uintptr_t(v) > 32);
666 return reinterpret_cast<gc::Cell*>(v);
668 static bool needsPostBarrier(JSObject* v) {
669 return v != nullptr && gc::IsInsideNursery(reinterpret_cast<gc::Cell*>(v));
671 static void postBarrier(JSObject** vp) {
672 JS::HeapCellPostBarrier(reinterpret_cast<js::gc::Cell**>(vp));
674 static void relocate(JSObject** vp) {
675 JS::HeapCellRelocate(reinterpret_cast<js::gc::Cell**>(vp));
679 template <>
680 struct GCMethods<JSFunction*>
682 static JSFunction* initial() { return nullptr; }
683 static bool poisoned(JSFunction* v) { return JS::IsPoisonedPtr(v); }
684 static bool needsPostBarrier(JSFunction* v) {
685 return v != nullptr && gc::IsInsideNursery(reinterpret_cast<gc::Cell*>(v));
687 static void postBarrier(JSFunction** vp) {
688 JS::HeapCellPostBarrier(reinterpret_cast<js::gc::Cell**>(vp));
690 static void relocate(JSFunction** vp) {
691 JS::HeapCellRelocate(reinterpret_cast<js::gc::Cell**>(vp));
695 } /* namespace js */
697 namespace JS {
700 * Local variable of type T whose value is always rooted. This is typically
701 * used for local variables, or for non-rooted values being passed to a
702 * function that requires a handle, e.g. Foo(Root<T>(cx, x)).
704 * If you want to add additional methods to Rooted for a specific
705 * specialization, define a RootedBase<T> specialization containing them.
707 template <typename T>
708 class MOZ_STACK_CLASS Rooted : public js::RootedBase<T>
710 /* Note: CX is a subclass of either ContextFriendFields or PerThreadDataFriendFields. */
711 template <typename CX>
712 void init(CX* cx) {
713 js::ThingRootKind kind = js::RootKind<T>::rootKind();
714 this->stack = &cx->thingGCRooters[kind];
715 this->prev = *stack;
716 *stack = reinterpret_cast<Rooted<void*>*>(this);
718 MOZ_ASSERT(!js::GCMethods<T>::poisoned(ptr));
721 public:
722 explicit Rooted(JSContext* cx
723 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
724 : ptr(js::GCMethods<T>::initial())
726 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
727 init(js::ContextFriendFields::get(cx));
730 Rooted(JSContext* cx, T initial
731 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
732 : ptr(initial)
734 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
735 init(js::ContextFriendFields::get(cx));
738 explicit Rooted(js::ContextFriendFields* cx
739 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
740 : ptr(js::GCMethods<T>::initial())
742 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
743 init(cx);
746 Rooted(js::ContextFriendFields* cx, T initial
747 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
748 : ptr(initial)
750 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
751 init(cx);
754 explicit Rooted(js::PerThreadDataFriendFields* pt
755 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
756 : ptr(js::GCMethods<T>::initial())
758 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
759 init(pt);
762 Rooted(js::PerThreadDataFriendFields* pt, T initial
763 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
764 : ptr(initial)
766 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
767 init(pt);
770 explicit Rooted(JSRuntime* rt
771 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
772 : ptr(js::GCMethods<T>::initial())
774 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
775 init(js::PerThreadDataFriendFields::getMainThread(rt));
778 Rooted(JSRuntime* rt, T initial
779 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
780 : ptr(initial)
782 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
783 init(js::PerThreadDataFriendFields::getMainThread(rt));
786 ~Rooted() {
787 MOZ_ASSERT(*stack == reinterpret_cast<Rooted<void*>*>(this));
788 *stack = prev;
791 Rooted<T>* previous() { return reinterpret_cast<Rooted<T>*>(prev); }
794 * Important: Return a reference here so passing a Rooted<T> to
795 * something that takes a |const T&| is not a GC hazard.
797 operator const T&() const { return ptr; }
798 T operator->() const { return ptr; }
799 T* address() { return &ptr; }
800 const T* address() const { return &ptr; }
801 T& get() { return ptr; }
802 const T& get() const { return ptr; }
804 T& operator=(T value) {
805 MOZ_ASSERT(!js::GCMethods<T>::poisoned(value));
806 ptr = value;
807 return ptr;
810 T& operator=(const Rooted& value) {
811 ptr = value;
812 return ptr;
815 void set(T value) {
816 MOZ_ASSERT(!js::GCMethods<T>::poisoned(value));
817 ptr = value;
820 bool operator!=(const T& other) const { return ptr != other; }
821 bool operator==(const T& other) const { return ptr == other; }
823 private:
825 * These need to be templated on void* to avoid aliasing issues between, for
826 * example, Rooted<JSObject> and Rooted<JSFunction>, which use the same
827 * stack head pointer for different classes.
829 Rooted<void*>** stack, *prev;
832 * |ptr| must be the last field in Rooted because the analysis treats all
833 * Rooted as Rooted<void*> during the analysis. See bug 829372.
835 T ptr;
837 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
839 Rooted(const Rooted&) = delete;
842 } /* namespace JS */
844 namespace js {
847 * Augment the generic Rooted<T> interface when T = JSObject* with
848 * class-querying and downcasting operations.
850 * Given a Rooted<JSObject*> obj, one can view
851 * Handle<StringObject*> h = obj.as<StringObject*>();
852 * as an optimization of
853 * Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
854 * Handle<StringObject*> h = rooted;
856 template <>
857 class RootedBase<JSObject*>
859 public:
860 template <class U>
861 JS::Handle<U*> as() const;
865 * Augment the generic Handle<T> interface when T = JSObject* with
866 * downcasting operations.
868 * Given a Handle<JSObject*> obj, one can view
869 * Handle<StringObject*> h = obj.as<StringObject*>();
870 * as an optimization of
871 * Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
872 * Handle<StringObject*> h = rooted;
874 template <>
875 class HandleBase<JSObject*>
877 public:
878 template <class U>
879 JS::Handle<U*> as() const;
882 /* Interface substitute for Rooted<T> which does not root the variable's memory. */
883 template <typename T>
884 class FakeRooted : public RootedBase<T>
886 public:
887 template <typename CX>
888 FakeRooted(CX* cx
889 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
890 : ptr(GCMethods<T>::initial())
892 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
895 template <typename CX>
896 FakeRooted(CX* cx, T initial
897 MOZ_GUARD_OBJECT_NOTIFIER_PARAM)
898 : ptr(initial)
900 MOZ_GUARD_OBJECT_NOTIFIER_INIT;
903 operator T() const { return ptr; }
904 T operator->() const { return ptr; }
905 T* address() { return &ptr; }
906 const T* address() const { return &ptr; }
907 T& get() { return ptr; }
908 const T& get() const { return ptr; }
910 FakeRooted<T>& operator=(T value) {
911 MOZ_ASSERT(!GCMethods<T>::poisoned(value));
912 ptr = value;
913 return *this;
916 FakeRooted<T>& operator=(const FakeRooted<T>& other) {
917 MOZ_ASSERT(!GCMethods<T>::poisoned(other.ptr));
918 ptr = other.ptr;
919 return *this;
922 bool operator!=(const T& other) const { return ptr != other; }
923 bool operator==(const T& other) const { return ptr == other; }
925 private:
926 T ptr;
928 MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
930 FakeRooted(const FakeRooted&) = delete;
933 /* Interface substitute for MutableHandle<T> which is not required to point to rooted memory. */
934 template <typename T>
935 class FakeMutableHandle : public js::MutableHandleBase<T>
937 public:
938 MOZ_IMPLICIT FakeMutableHandle(T* t) {
939 ptr = t;
942 MOZ_IMPLICIT FakeMutableHandle(FakeRooted<T>* root) {
943 ptr = root->address();
946 void set(T v) {
947 MOZ_ASSERT(!js::GCMethods<T>::poisoned(v));
948 *ptr = v;
951 T* address() const { return ptr; }
952 T get() const { return *ptr; }
954 operator T() const { return get(); }
955 T operator->() const { return get(); }
957 private:
958 FakeMutableHandle() {}
960 T* ptr;
962 template <typename S>
963 void operator=(S v) = delete;
965 void operator=(const FakeMutableHandle<T>& other) = delete;
969 * Types for a variable that either should or shouldn't be rooted, depending on
970 * the template parameter allowGC. Used for implementing functions that can
971 * operate on either rooted or unrooted data.
973 * The toHandle() and toMutableHandle() functions are for calling functions
974 * which require handle types and are only called in the CanGC case. These
975 * allow the calling code to type check.
977 enum AllowGC {
978 NoGC = 0,
979 CanGC = 1
981 template <typename T, AllowGC allowGC>
982 class MaybeRooted
986 template <typename T> class MaybeRooted<T, CanGC>
988 public:
989 typedef JS::Handle<T> HandleType;
990 typedef JS::Rooted<T> RootType;
991 typedef JS::MutableHandle<T> MutableHandleType;
993 static inline JS::Handle<T> toHandle(HandleType v) {
994 return v;
997 static inline JS::MutableHandle<T> toMutableHandle(MutableHandleType v) {
998 return v;
1001 template <typename T2>
1002 static inline JS::Handle<T2*> downcastHandle(HandleType v) {
1003 return v.template as<T2>();
1007 template <typename T> class MaybeRooted<T, NoGC>
1009 public:
1010 typedef T HandleType;
1011 typedef FakeRooted<T> RootType;
1012 typedef FakeMutableHandle<T> MutableHandleType;
1014 static JS::Handle<T> toHandle(HandleType v) {
1015 MOZ_CRASH("Bad conversion");
1018 static JS::MutableHandle<T> toMutableHandle(MutableHandleType v) {
1019 MOZ_CRASH("Bad conversion");
1022 template <typename T2>
1023 static inline T2* downcastHandle(HandleType v) {
1024 return &v->template as<T2>();
1028 } /* namespace js */
1030 namespace JS {
1032 template <typename T> template <typename S>
1033 inline
1034 Handle<T>::Handle(const Rooted<S>& root,
1035 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy)
1037 ptr = reinterpret_cast<const T*>(root.address());
1040 template <typename T> template <typename S>
1041 inline
1042 Handle<T>::Handle(const PersistentRooted<S>& root,
1043 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy)
1045 ptr = reinterpret_cast<const T*>(root.address());
1048 template <typename T> template <typename S>
1049 inline
1050 Handle<T>::Handle(MutableHandle<S>& root,
1051 typename mozilla::EnableIf<mozilla::IsConvertible<S, T>::value, int>::Type dummy)
1053 ptr = reinterpret_cast<const T*>(root.address());
1056 template <typename T>
1057 inline
1058 MutableHandle<T>::MutableHandle(Rooted<T>* root)
1060 static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1061 "MutableHandle must be binary compatible with T*.");
1062 ptr = root->address();
1065 template <typename T>
1066 inline
1067 MutableHandle<T>::MutableHandle(PersistentRooted<T>* root)
1069 static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1070 "MutableHandle must be binary compatible with T*.");
1071 ptr = root->address();
1075 * A copyable, assignable global GC root type with arbitrary lifetime, an
1076 * infallible constructor, and automatic unrooting on destruction.
1078 * These roots can be used in heap-allocated data structures, so they are not
1079 * associated with any particular JSContext or stack. They are registered with
1080 * the JSRuntime itself, without locking, so they require a full JSContext to be
1081 * constructed, not one of its more restricted superclasses.
1083 * Note that you must not use an PersistentRooted in an object owned by a JS
1084 * object:
1086 * Whenever one object whose lifetime is decided by the GC refers to another
1087 * such object, that edge must be traced only if the owning JS object is traced.
1088 * This applies not only to JS objects (which obviously are managed by the GC)
1089 * but also to C++ objects owned by JS objects.
1091 * If you put a PersistentRooted in such a C++ object, that is almost certainly
1092 * a leak. When a GC begins, the referent of the PersistentRooted is treated as
1093 * live, unconditionally (because a PersistentRooted is a *root*), even if the
1094 * JS object that owns it is unreachable. If there is any path from that
1095 * referent back to the JS object, then the C++ object containing the
1096 * PersistentRooted will not be destructed, and the whole blob of objects will
1097 * not be freed, even if there are no references to them from the outside.
1099 * In the context of Firefox, this is a severe restriction: almost everything in
1100 * Firefox is owned by some JS object or another, so using PersistentRooted in
1101 * such objects would introduce leaks. For these kinds of edges, Heap<T> or
1102 * TenuredHeap<T> would be better types. It's up to the implementor of the type
1103 * containing Heap<T> or TenuredHeap<T> members to make sure their referents get
1104 * marked when the object itself is marked.
1106 template<typename T>
1107 class PersistentRooted : private mozilla::LinkedListElement<PersistentRooted<T> > {
1108 friend class mozilla::LinkedList<PersistentRooted>;
1109 friend class mozilla::LinkedListElement<PersistentRooted>;
1111 friend struct js::gc::PersistentRootedMarker<T>;
1113 void registerWithRuntime(JSRuntime* rt) {
1114 JS::shadow::Runtime* srt = JS::shadow::Runtime::asShadowRuntime(rt);
1115 srt->getPersistentRootedList<T>().insertBack(this);
1118 public:
1119 explicit PersistentRooted(JSContext* cx) : ptr(js::GCMethods<T>::initial())
1121 registerWithRuntime(js::GetRuntime(cx));
1124 PersistentRooted(JSContext* cx, T initial) : ptr(initial)
1126 registerWithRuntime(js::GetRuntime(cx));
1129 explicit PersistentRooted(JSRuntime* rt) : ptr(js::GCMethods<T>::initial())
1131 registerWithRuntime(rt);
1134 PersistentRooted(JSRuntime* rt, T initial) : ptr(initial)
1136 registerWithRuntime(rt);
1139 PersistentRooted(const PersistentRooted& rhs)
1140 : mozilla::LinkedListElement<PersistentRooted<T> >(),
1141 ptr(rhs.ptr)
1144 * Copy construction takes advantage of the fact that the original
1145 * is already inserted, and simply adds itself to whatever list the
1146 * original was on - no JSRuntime pointer needed.
1148 * This requires mutating rhs's links, but those should be 'mutable'
1149 * anyway. C++ doesn't let us declare mutable base classes.
1151 const_cast<PersistentRooted&>(rhs).setNext(this);
1155 * Important: Return a reference here so passing a Rooted<T> to
1156 * something that takes a |const T&| is not a GC hazard.
1158 operator const T&() const { return ptr; }
1159 T operator->() const { return ptr; }
1160 T* address() { return &ptr; }
1161 const T* address() const { return &ptr; }
1162 T& get() { return ptr; }
1163 const T& get() const { return ptr; }
1165 T& operator=(T value) {
1166 MOZ_ASSERT(!js::GCMethods<T>::poisoned(value));
1167 ptr = value;
1168 return ptr;
1171 T& operator=(const PersistentRooted& value) {
1172 ptr = value;
1173 return ptr;
1176 void set(T value) {
1177 MOZ_ASSERT(!js::GCMethods<T>::poisoned(value));
1178 ptr = value;
1181 bool operator!=(const T& other) const { return ptr != other; }
1182 bool operator==(const T& other) const { return ptr == other; }
1184 private:
1185 T ptr;
1188 class JS_PUBLIC_API(ObjectPtr)
1190 Heap<JSObject*> value;
1192 public:
1193 ObjectPtr() : value(nullptr) {}
1195 explicit ObjectPtr(JSObject* obj) : value(obj) {}
1197 /* Always call finalize before the destructor. */
1198 ~ObjectPtr() { MOZ_ASSERT(!value); }
1200 void finalize(JSRuntime* rt) {
1201 if (IsIncrementalBarrierNeeded(rt))
1202 IncrementalObjectBarrier(value);
1203 value = nullptr;
1206 void init(JSObject* obj) { value = obj; }
1208 JSObject* get() const { return value; }
1210 void writeBarrierPre(JSRuntime* rt) {
1211 IncrementalObjectBarrier(value);
1214 void updateWeakPointerAfterGC();
1216 ObjectPtr& operator=(JSObject* obj) {
1217 IncrementalObjectBarrier(value);
1218 value = obj;
1219 return *this;
1222 void trace(JSTracer* trc, const char* name);
1224 JSObject& operator*() const { return *value; }
1225 JSObject* operator->() const { return value; }
1226 operator JSObject*() const { return value; }
1229 } /* namespace JS */
1231 namespace js {
1232 namespace gc {
1234 template <typename T, typename TraceCallbacks>
1235 void
1236 CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks, const char* aName, void* aClosure)
1238 static_assert(sizeof(T) == sizeof(JS::Heap<T>), "T and Heap<T> must be compatible.");
1239 MOZ_ASSERT(v);
1240 mozilla::DebugOnly<Cell*> cell = GCMethods<T>::asGCThingOrNull(*v);
1241 MOZ_ASSERT(cell);
1242 MOZ_ASSERT(!IsInsideNursery(cell));
1243 JS::Heap<T>* asHeapT = reinterpret_cast<JS::Heap<T>*>(v);
1244 aCallbacks.Trace(asHeapT, aName, aClosure);
1247 } /* namespace gc */
1249 } /* namespace js */
1251 #endif /* js_RootingAPI_h */