Source code

Revision control

Other Tools

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 js_RootingAPI_h
8
#define js_RootingAPI_h
9
10
#include "mozilla/Attributes.h"
11
#include "mozilla/DebugOnly.h"
12
#include "mozilla/GuardObjects.h"
13
#include "mozilla/LinkedList.h"
14
15
#include <type_traits>
16
#include <utility>
17
18
#include "jspubtd.h"
19
20
#include "js/ComparisonOperators.h" // JS::detail::DefineComparisonOps
21
#include "js/GCAnnotations.h"
22
#include "js/GCPolicyAPI.h"
23
#include "js/GCTypeMacros.h" // JS_FOR_EACH_PUBLIC_{,TAGGED_}GC_POINTER_TYPE
24
#include "js/HeapAPI.h"
25
#include "js/ProfilingStack.h"
26
#include "js/Realm.h"
27
#include "js/TypeDecls.h"
28
#include "js/UniquePtr.h"
29
#include "js/Utility.h"
30
31
/*
32
* [SMDOC] Stack Rooting
33
*
34
* Moving GC Stack Rooting
35
*
36
* A moving GC may change the physical location of GC allocated things, even
37
* when they are rooted, updating all pointers to the thing to refer to its new
38
* location. The GC must therefore know about all live pointers to a thing,
39
* not just one of them, in order to behave correctly.
40
*
41
* The |Rooted| and |Handle| classes below are used to root stack locations
42
* whose value may be held live across a call that can trigger GC. For a
43
* code fragment such as:
44
*
45
* JSObject* obj = NewObject(cx);
46
* DoSomething(cx);
47
* ... = obj->lastProperty();
48
*
49
* If |DoSomething()| can trigger a GC, the stack location of |obj| must be
50
* rooted to ensure that the GC does not move the JSObject referred to by
51
* |obj| without updating |obj|'s location itself. This rooting must happen
52
* regardless of whether there are other roots which ensure that the object
53
* itself will not be collected.
54
*
55
* If |DoSomething()| cannot trigger a GC, and the same holds for all other
56
* calls made between |obj|'s definitions and its last uses, then no rooting
57
* is required.
58
*
59
* SpiderMonkey can trigger a GC at almost any time and in ways that are not
60
* always clear. For example, the following innocuous-looking actions can
61
* cause a GC: allocation of any new GC thing; JSObject::hasProperty;
62
* JS_ReportError and friends; and ToNumber, among many others. The following
63
* dangerous-looking actions cannot trigger a GC: js_malloc, cx->malloc_,
64
* rt->malloc_, and friends and JS_ReportOutOfMemory.
65
*
66
* The following family of three classes will exactly root a stack location.
67
* Incorrect usage of these classes will result in a compile error in almost
68
* all cases. Therefore, it is very hard to be incorrectly rooted if you use
69
* these classes exclusively. These classes are all templated on the type T of
70
* the value being rooted.
71
*
72
* - Rooted<T> declares a variable of type T, whose value is always rooted.
73
* Rooted<T> may be automatically coerced to a Handle<T>, below. Rooted<T>
74
* should be used whenever a local variable's value may be held live across a
75
* call which can trigger a GC.
76
*
77
* - Handle<T> is a const reference to a Rooted<T>. Functions which take GC
78
* things or values as arguments and need to root those arguments should
79
* generally use handles for those arguments and avoid any explicit rooting.
80
* This has two benefits. First, when several such functions call each other
81
* then redundant rooting of multiple copies of the GC thing can be avoided.
82
* Second, if the caller does not pass a rooted value a compile error will be
83
* generated, which is quicker and easier to fix than when relying on a
84
* separate rooting analysis.
85
*
86
* - MutableHandle<T> is a non-const reference to Rooted<T>. It is used in the
87
* same way as Handle<T> and includes a |set(const T& v)| method to allow
88
* updating the value of the referenced Rooted<T>. A MutableHandle<T> can be
89
* created with an implicit cast from a Rooted<T>*.
90
*
91
* In some cases the small performance overhead of exact rooting (measured to
92
* be a few nanoseconds on desktop) is too much. In these cases, try the
93
* following:
94
*
95
* - Move all Rooted<T> above inner loops: this allows you to re-use the root
96
* on each iteration of the loop.
97
*
98
* - Pass Handle<T> through your hot call stack to avoid re-rooting costs at
99
* every invocation.
100
*
101
* The following diagram explains the list of supported, implicit type
102
* conversions between classes of this family:
103
*
104
* Rooted<T> ----> Handle<T>
105
* | ^
106
* | |
107
* | |
108
* +---> MutableHandle<T>
109
* (via &)
110
*
111
* All of these types have an implicit conversion to raw pointers.
112
*/
113
114
namespace js {
115
116
template <typename T>
117
struct BarrierMethods {};
118
119
template <typename Element, typename Wrapper>
120
class WrappedPtrOperations {};
121
122
template <typename Element, typename Wrapper>
123
class MutableWrappedPtrOperations
124
: public WrappedPtrOperations<Element, Wrapper> {};
125
126
template <typename T, typename Wrapper>
127
class RootedBase : public MutableWrappedPtrOperations<T, Wrapper> {};
128
129
template <typename T, typename Wrapper>
130
class HandleBase : public WrappedPtrOperations<T, Wrapper> {};
131
132
template <typename T, typename Wrapper>
133
class MutableHandleBase : public MutableWrappedPtrOperations<T, Wrapper> {};
134
135
template <typename T, typename Wrapper>
136
class HeapBase : public MutableWrappedPtrOperations<T, Wrapper> {};
137
138
// Cannot use FOR_EACH_HEAP_ABLE_GC_POINTER_TYPE, as this would import too many
139
// macros into scope
140
template <typename T>
141
struct IsHeapConstructibleType {
142
static constexpr bool value = false;
143
};
144
#define DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE(T) \
145
template <> \
146
struct IsHeapConstructibleType<T> { \
147
static constexpr bool value = true; \
148
};
149
JS_FOR_EACH_PUBLIC_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE)
150
JS_FOR_EACH_PUBLIC_TAGGED_GC_POINTER_TYPE(DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE)
151
#undef DECLARE_IS_HEAP_CONSTRUCTIBLE_TYPE
152
153
template <typename T, typename Wrapper>
154
class PersistentRootedBase : public MutableWrappedPtrOperations<T, Wrapper> {};
155
156
namespace gc {
157
struct Cell;
158
template <typename T>
159
struct PersistentRootedMarker;
160
} /* namespace gc */
161
162
// Important: Return a reference so passing a Rooted<T>, etc. to
163
// something that takes a |const T&| is not a GC hazard.
164
#define DECLARE_POINTER_CONSTREF_OPS(T) \
165
operator const T&() const { return get(); } \
166
const T& operator->() const { return get(); }
167
168
// Assignment operators on a base class are hidden by the implicitly defined
169
// operator= on the derived class. Thus, define the operator= directly on the
170
// class as we would need to manually pass it through anyway.
171
#define DECLARE_POINTER_ASSIGN_OPS(Wrapper, T) \
172
Wrapper<T>& operator=(const T& p) { \
173
set(p); \
174
return *this; \
175
} \
176
Wrapper<T>& operator=(T&& p) { \
177
set(std::move(p)); \
178
return *this; \
179
} \
180
Wrapper<T>& operator=(const Wrapper<T>& other) { \
181
set(other.get()); \
182
return *this; \
183
}
184
185
#define DELETE_ASSIGNMENT_OPS(Wrapper, T) \
186
template <typename S> \
187
Wrapper<T>& operator=(S) = delete; \
188
Wrapper<T>& operator=(const Wrapper<T>&) = delete;
189
190
#define DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr) \
191
const T* address() const { return &(ptr); } \
192
const T& get() const { return (ptr); }
193
194
#define DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr) \
195
T* address() { return &(ptr); } \
196
T& get() { return (ptr); }
197
198
} /* namespace js */
199
200
namespace JS {
201
202
JS_FRIEND_API void HeapObjectPostWriteBarrier(JSObject** objp, JSObject* prev,
203
JSObject* next);
204
JS_FRIEND_API void HeapStringPostWriteBarrier(JSString** objp, JSString* prev,
205
JSString* next);
206
JS_FRIEND_API void HeapBigIntPostWriteBarrier(JS::BigInt** bip,
207
JS::BigInt* prev,
208
JS::BigInt* next);
209
JS_FRIEND_API void HeapObjectWriteBarriers(JSObject** objp, JSObject* prev,
210
JSObject* next);
211
JS_FRIEND_API void HeapStringWriteBarriers(JSString** objp, JSString* prev,
212
JSString* next);
213
JS_FRIEND_API void HeapBigIntWriteBarriers(JS::BigInt** bip, JS::BigInt* prev,
214
JS::BigInt* next);
215
JS_FRIEND_API void HeapScriptWriteBarriers(JSScript** objp, JSScript* prev,
216
JSScript* next);
217
218
/**
219
* Create a safely-initialized |T|, suitable for use as a default value in
220
* situations requiring a safe but arbitrary |T| value.
221
*/
222
template <typename T>
223
inline T SafelyInitialized() {
224
// This function wants to presume that |T()| -- which value-initializes a
225
// |T| per C++11 [expr.type.conv]p2 -- will produce a safely-initialized,
226
// safely-usable T that it can return.
227
228
#if defined(XP_WIN) || defined(XP_MACOSX) || \
229
(defined(XP_UNIX) && !defined(__clang__))
230
231
// That presumption holds for pointers, where value initialization produces
232
// a null pointer.
233
constexpr bool IsPointer = std::is_pointer<T>::value;
234
235
// For classes and unions we *assume* that if |T|'s default constructor is
236
// non-trivial it'll initialize correctly. (This is unideal, but C++
237
// doesn't offer a type trait indicating whether a class's constructor is
238
// user-defined, which better approximates our desired semantics.)
239
constexpr bool IsNonTriviallyDefaultConstructibleClassOrUnion =
240
(std::is_class<T>::value || std::is_union<T>::value) &&
241
!std::is_trivially_default_constructible<T>::value;
242
243
static_assert(IsPointer || IsNonTriviallyDefaultConstructibleClassOrUnion,
244
"T() must evaluate to a safely-initialized T");
245
246
#endif
247
248
return T();
249
}
250
251
#ifdef JS_DEBUG
252
/**
253
* For generational GC, assert that an object is in the tenured generation as
254
* opposed to being in the nursery.
255
*/
256
extern JS_FRIEND_API void AssertGCThingMustBeTenured(JSObject* obj);
257
extern JS_FRIEND_API void AssertGCThingIsNotNurseryAllocable(
258
js::gc::Cell* cell);
259
#else
260
inline void AssertGCThingMustBeTenured(JSObject* obj) {}
261
inline void AssertGCThingIsNotNurseryAllocable(js::gc::Cell* cell) {}
262
#endif
263
264
/**
265
* The Heap<T> class is a heap-stored reference to a JS GC thing for use outside
266
* the JS engine. All members of heap classes that refer to GC things should use
267
* Heap<T> (or possibly TenuredHeap<T>, described below).
268
*
269
* Heap<T> is an abstraction that hides some of the complexity required to
270
* maintain GC invariants for the contained reference. It uses operator
271
* overloading to provide a normal pointer interface, but adds barriers to
272
* notify the GC of changes.
273
*
274
* Heap<T> implements the following barriers:
275
*
276
* - Post-write barrier (necessary for generational GC).
277
* - Read barrier (necessary for incremental GC and cycle collector
278
* integration).
279
*
280
* Note Heap<T> does not have a pre-write barrier as used internally in the
281
* engine. The read barrier is used to mark anything read from a Heap<T> during
282
* an incremental GC.
283
*
284
* Heap<T> may be moved or destroyed outside of GC finalization and hence may be
285
* used in dynamic storage such as a Vector.
286
*
287
* Heap<T> instances must be traced when their containing object is traced to
288
* keep the pointed-to GC thing alive.
289
*
290
* Heap<T> objects should only be used on the heap. GC references stored on the
291
* C/C++ stack must use Rooted/Handle/MutableHandle instead.
292
*
293
* Type T must be a public GC pointer type.
294
*/
295
template <typename T>
296
class MOZ_NON_MEMMOVABLE Heap : public js::HeapBase<T, Heap<T>> {
297
// Please note: this can actually also be used by nsXBLMaybeCompiled<T>, for
298
// legacy reasons.
299
static_assert(js::IsHeapConstructibleType<T>::value,
300
"Type T must be a public GC pointer type");
301
302
public:
303
using ElementType = T;
304
305
Heap() : ptr(SafelyInitialized<T>()) {
306
// No barriers are required for initialization to the default value.
307
static_assert(sizeof(T) == sizeof(Heap<T>),
308
"Heap<T> must be binary compatible with T.");
309
}
310
explicit Heap(const T& p) { init(p); }
311
312
/*
313
* For Heap, move semantics are equivalent to copy semantics. In C++, a
314
* copy constructor taking const-ref is the way to get a single function
315
* that will be used for both lvalue and rvalue copies, so we can simply
316
* omit the rvalue variant.
317
*/
318
explicit Heap(const Heap<T>& other) { init(other.ptr); }
319
320
Heap& operator=(Heap<T>&& other) {
321
set(other.unbarrieredGet());
322
other.set(SafelyInitialized<T>());
323
return *this;
324
}
325
326
~Heap() { postWriteBarrier(ptr, SafelyInitialized<T>()); }
327
328
DECLARE_POINTER_CONSTREF_OPS(T);
329
DECLARE_POINTER_ASSIGN_OPS(Heap, T);
330
331
const T* address() const { return &ptr; }
332
333
void exposeToActiveJS() const { js::BarrierMethods<T>::exposeToJS(ptr); }
334
const T& get() const {
335
exposeToActiveJS();
336
return ptr;
337
}
338
const T& unbarrieredGet() const { return ptr; }
339
340
void set(const T& newPtr) {
341
T tmp = ptr;
342
ptr = newPtr;
343
postWriteBarrier(tmp, ptr);
344
}
345
346
T* unsafeGet() { return &ptr; }
347
348
void unbarrieredSet(const T& newPtr) { ptr = newPtr; }
349
350
explicit operator bool() const {
351
return bool(js::BarrierMethods<T>::asGCThingOrNull(ptr));
352
}
353
explicit operator bool() {
354
return bool(js::BarrierMethods<T>::asGCThingOrNull(ptr));
355
}
356
357
private:
358
void init(const T& newPtr) {
359
ptr = newPtr;
360
postWriteBarrier(SafelyInitialized<T>(), ptr);
361
}
362
363
void postWriteBarrier(const T& prev, const T& next) {
364
js::BarrierMethods<T>::postWriteBarrier(&ptr, prev, next);
365
}
366
367
T ptr;
368
};
369
370
namespace detail {
371
372
template <typename T>
373
struct DefineComparisonOps<Heap<T>> : std::true_type {
374
static const T& get(const Heap<T>& v) { return v.unbarrieredGet(); }
375
};
376
377
} // namespace detail
378
379
static MOZ_ALWAYS_INLINE bool ObjectIsTenured(JSObject* obj) {
380
return !js::gc::IsInsideNursery(reinterpret_cast<js::gc::Cell*>(obj));
381
}
382
383
static MOZ_ALWAYS_INLINE bool ObjectIsTenured(const Heap<JSObject*>& obj) {
384
return ObjectIsTenured(obj.unbarrieredGet());
385
}
386
387
static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(JSObject* obj) {
388
auto cell = reinterpret_cast<js::gc::Cell*>(obj);
389
return js::gc::detail::CellIsMarkedGrayIfKnown(cell);
390
}
391
392
static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(
393
const JS::Heap<JSObject*>& obj) {
394
return ObjectIsMarkedGray(obj.unbarrieredGet());
395
}
396
397
// The following *IsNotGray functions take account of the eventual
398
// gray marking state at the end of any ongoing incremental GC by
399
// delaying the checks if necessary.
400
401
#ifdef DEBUG
402
403
inline void AssertCellIsNotGray(const js::gc::Cell* maybeCell) {
404
if (maybeCell) {
405
js::gc::detail::AssertCellIsNotGray(maybeCell);
406
}
407
}
408
409
inline void AssertObjectIsNotGray(JSObject* maybeObj) {
410
AssertCellIsNotGray(reinterpret_cast<js::gc::Cell*>(maybeObj));
411
}
412
413
inline void AssertObjectIsNotGray(const JS::Heap<JSObject*>& obj) {
414
AssertObjectIsNotGray(obj.unbarrieredGet());
415
}
416
417
#else
418
419
inline void AssertCellIsNotGray(js::gc::Cell* maybeCell) {}
420
inline void AssertObjectIsNotGray(JSObject* maybeObj) {}
421
inline void AssertObjectIsNotGray(const JS::Heap<JSObject*>& obj) {}
422
423
#endif
424
425
/**
426
* The TenuredHeap<T> class is similar to the Heap<T> class above in that it
427
* encapsulates the GC concerns of an on-heap reference to a JS object. However,
428
* it has two important differences:
429
*
430
* 1) Pointers which are statically known to only reference "tenured" objects
431
* can avoid the extra overhead of SpiderMonkey's write barriers.
432
*
433
* 2) Objects in the "tenured" heap have stronger alignment restrictions than
434
* those in the "nursery", so it is possible to store flags in the lower
435
* bits of pointers known to be tenured. TenuredHeap wraps a normal tagged
436
* pointer with a nice API for accessing the flag bits and adds various
437
* assertions to ensure that it is not mis-used.
438
*
439
* GC things are said to be "tenured" when they are located in the long-lived
440
* heap: e.g. they have gained tenure as an object by surviving past at least
441
* one GC. For performance, SpiderMonkey allocates some things which are known
442
* to normally be long lived directly into the tenured generation; for example,
443
* global objects. Additionally, SpiderMonkey does not visit individual objects
444
* when deleting non-tenured objects, so object with finalizers are also always
445
* tenured; for instance, this includes most DOM objects.
446
*
447
* The considerations to keep in mind when using a TenuredHeap<T> vs a normal
448
* Heap<T> are:
449
*
450
* - It is invalid for a TenuredHeap<T> to refer to a non-tenured thing.
451
* - It is however valid for a Heap<T> to refer to a tenured thing.
452
* - It is not possible to store flag bits in a Heap<T>.
453
*/
454
template <typename T>
455
class TenuredHeap : public js::HeapBase<T, TenuredHeap<T>> {
456
public:
457
using ElementType = T;
458
459
TenuredHeap() : bits(0) {
460
static_assert(sizeof(T) == sizeof(TenuredHeap<T>),
461
"TenuredHeap<T> must be binary compatible with T.");
462
}
463
explicit TenuredHeap(T p) : bits(0) { setPtr(p); }
464
explicit TenuredHeap(const TenuredHeap<T>& p) : bits(0) {
465
setPtr(p.getPtr());
466
}
467
468
void setPtr(T newPtr) {
469
MOZ_ASSERT((reinterpret_cast<uintptr_t>(newPtr) & flagsMask) == 0);
470
MOZ_ASSERT(js::gc::IsCellPointerValidOrNull(newPtr));
471
if (newPtr) {
472
AssertGCThingMustBeTenured(newPtr);
473
}
474
bits = (bits & flagsMask) | reinterpret_cast<uintptr_t>(newPtr);
475
}
476
477
void setFlags(uintptr_t flagsToSet) {
478
MOZ_ASSERT((flagsToSet & ~flagsMask) == 0);
479
bits |= flagsToSet;
480
}
481
482
void unsetFlags(uintptr_t flagsToUnset) {
483
MOZ_ASSERT((flagsToUnset & ~flagsMask) == 0);
484
bits &= ~flagsToUnset;
485
}
486
487
bool hasFlag(uintptr_t flag) const {
488
MOZ_ASSERT((flag & ~flagsMask) == 0);
489
return (bits & flag) != 0;
490
}
491
492
T unbarrieredGetPtr() const { return reinterpret_cast<T>(bits & ~flagsMask); }
493
uintptr_t getFlags() const { return bits & flagsMask; }
494
495
void exposeToActiveJS() const {
496
js::BarrierMethods<T>::exposeToJS(unbarrieredGetPtr());
497
}
498
T getPtr() const {
499
exposeToActiveJS();
500
return unbarrieredGetPtr();
501
}
502
503
operator T() const { return getPtr(); }
504
T operator->() const { return getPtr(); }
505
506
explicit operator bool() const {
507
return bool(js::BarrierMethods<T>::asGCThingOrNull(unbarrieredGetPtr()));
508
}
509
explicit operator bool() {
510
return bool(js::BarrierMethods<T>::asGCThingOrNull(unbarrieredGetPtr()));
511
}
512
513
TenuredHeap<T>& operator=(T p) {
514
setPtr(p);
515
return *this;
516
}
517
518
TenuredHeap<T>& operator=(const TenuredHeap<T>& other) {
519
bits = other.bits;
520
return *this;
521
}
522
523
private:
524
enum {
525
maskBits = 3,
526
flagsMask = (1 << maskBits) - 1,
527
};
528
529
uintptr_t bits;
530
};
531
532
namespace detail {
533
534
template <typename T>
535
struct DefineComparisonOps<TenuredHeap<T>> : std::true_type {
536
static const T get(const TenuredHeap<T>& v) { return v.unbarrieredGetPtr(); }
537
};
538
539
} // namespace detail
540
541
// std::swap uses a stack temporary, which prevents classes like Heap<T>
542
// from being declared MOZ_HEAP_CLASS.
543
template <typename T>
544
void swap(TenuredHeap<T>& aX, TenuredHeap<T>& aY) {
545
T tmp = aX;
546
aX = aY;
547
aY = tmp;
548
}
549
550
template <typename T>
551
void swap(Heap<T>& aX, Heap<T>& aY) {
552
T tmp = aX;
553
aX = aY;
554
aY = tmp;
555
}
556
557
static MOZ_ALWAYS_INLINE bool ObjectIsMarkedGray(
558
const JS::TenuredHeap<JSObject*>& obj) {
559
return ObjectIsMarkedGray(obj.unbarrieredGetPtr());
560
}
561
562
template <typename T>
563
class MutableHandle;
564
template <typename T>
565
class Rooted;
566
template <typename T>
567
class PersistentRooted;
568
569
/**
570
* Reference to a T that has been rooted elsewhere. This is most useful
571
* as a parameter type, which guarantees that the T lvalue is properly
572
* rooted. See "Move GC Stack Rooting" above.
573
*
574
* If you want to add additional methods to Handle for a specific
575
* specialization, define a HandleBase<T> specialization containing them.
576
*/
577
template <typename T>
578
class MOZ_NONHEAP_CLASS Handle : public js::HandleBase<T, Handle<T>> {
579
friend class MutableHandle<T>;
580
581
public:
582
using ElementType = T;
583
584
/* Creates a handle from a handle of a type convertible to T. */
585
template <typename S>
586
MOZ_IMPLICIT Handle(
587
Handle<S> handle,
588
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0) {
589
static_assert(sizeof(Handle<T>) == sizeof(T*),
590
"Handle must be binary compatible with T*.");
591
ptr = reinterpret_cast<const T*>(handle.address());
592
}
593
594
MOZ_IMPLICIT Handle(decltype(nullptr)) {
595
static_assert(std::is_pointer_v<T>,
596
"nullptr_t overload not valid for non-pointer types");
597
static void* const ConstNullValue = nullptr;
598
ptr = reinterpret_cast<const T*>(&ConstNullValue);
599
}
600
601
MOZ_IMPLICIT Handle(MutableHandle<T> handle) { ptr = handle.address(); }
602
603
/*
604
* Take care when calling this method!
605
*
606
* This creates a Handle from the raw location of a T.
607
*
608
* It should be called only if the following conditions hold:
609
*
610
* 1) the location of the T is guaranteed to be marked (for some reason
611
* other than being a Rooted), e.g., if it is guaranteed to be reachable
612
* from an implicit root.
613
*
614
* 2) the contents of the location are immutable, or at least cannot change
615
* for the lifetime of the handle, as its users may not expect its value
616
* to change underneath them.
617
*/
618
static constexpr Handle fromMarkedLocation(const T* p) {
619
return Handle(p, DeliberatelyChoosingThisOverload,
620
ImUsingThisOnlyInFromFromMarkedLocation);
621
}
622
623
/*
624
* Construct a handle from an explicitly rooted location. This is the
625
* normal way to create a handle, and normally happens implicitly.
626
*/
627
template <typename S>
628
inline MOZ_IMPLICIT Handle(
629
const Rooted<S>& root,
630
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
631
632
template <typename S>
633
inline MOZ_IMPLICIT Handle(
634
const PersistentRooted<S>& root,
635
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
636
637
/* Construct a read only handle from a mutable handle. */
638
template <typename S>
639
inline MOZ_IMPLICIT Handle(
640
MutableHandle<S>& root,
641
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy = 0);
642
643
DECLARE_POINTER_CONSTREF_OPS(T);
644
DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr);
645
646
private:
647
Handle() = default;
648
DELETE_ASSIGNMENT_OPS(Handle, T);
649
650
enum Disambiguator { DeliberatelyChoosingThisOverload = 42 };
651
enum CallerIdentity { ImUsingThisOnlyInFromFromMarkedLocation = 17 };
652
constexpr Handle(const T* p, Disambiguator, CallerIdentity) : ptr(p) {}
653
654
const T* ptr;
655
};
656
657
namespace detail {
658
659
template <typename T>
660
struct DefineComparisonOps<Handle<T>> : std::true_type {
661
static const T& get(const Handle<T>& v) { return v.get(); }
662
};
663
664
} // namespace detail
665
666
/**
667
* Similar to a handle, but the underlying storage can be changed. This is
668
* useful for outparams.
669
*
670
* If you want to add additional methods to MutableHandle for a specific
671
* specialization, define a MutableHandleBase<T> specialization containing
672
* them.
673
*/
674
template <typename T>
675
class MOZ_STACK_CLASS MutableHandle
676
: public js::MutableHandleBase<T, MutableHandle<T>> {
677
public:
678
using ElementType = T;
679
680
inline MOZ_IMPLICIT MutableHandle(Rooted<T>* root);
681
inline MOZ_IMPLICIT MutableHandle(PersistentRooted<T>* root);
682
683
private:
684
// Disallow nullptr for overloading purposes.
685
MutableHandle(decltype(nullptr)) = delete;
686
687
public:
688
void set(const T& v) {
689
*ptr = v;
690
MOZ_ASSERT(GCPolicy<T>::isValid(*ptr));
691
}
692
void set(T&& v) {
693
*ptr = std::move(v);
694
MOZ_ASSERT(GCPolicy<T>::isValid(*ptr));
695
}
696
697
/*
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.
701
*
702
* Create a MutableHandle from a raw location of a T.
703
*/
704
static MutableHandle fromMarkedLocation(T* p) {
705
MutableHandle h;
706
h.ptr = p;
707
return h;
708
}
709
710
DECLARE_POINTER_CONSTREF_OPS(T);
711
DECLARE_NONPOINTER_ACCESSOR_METHODS(*ptr);
712
DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(*ptr);
713
714
private:
715
MutableHandle() = default;
716
DELETE_ASSIGNMENT_OPS(MutableHandle, T);
717
718
T* ptr;
719
};
720
721
namespace detail {
722
723
template <typename T>
724
struct DefineComparisonOps<MutableHandle<T>> : std::true_type {
725
static const T& get(const MutableHandle<T>& v) { return v.get(); }
726
};
727
728
} // namespace detail
729
730
} /* namespace JS */
731
732
namespace js {
733
734
namespace detail {
735
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;
743
}
744
MOZ_ASSERT(uintptr_t(v) > 32);
745
return reinterpret_cast<gc::Cell*>(v);
746
}
747
static void exposeToJS(T* t) {
748
if (t) {
749
js::gc::ExposeGCThingToActiveJS(JS::GCCellPtr(t));
750
}
751
}
752
};
753
754
} // namespace detail
755
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));
762
}
763
}
764
};
765
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);
771
}
772
static void exposeToJS(JSObject* obj) {
773
if (obj) {
774
JS::ExposeObjectToActiveJS(obj);
775
}
776
}
777
};
778
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));
787
}
788
static void exposeToJS(JSFunction* fun) {
789
if (fun) {
790
JS::ExposeObjectToActiveJS(reinterpret_cast<JSObject*>(fun));
791
}
792
}
793
};
794
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);
800
}
801
};
802
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);
809
}
810
};
811
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.
816
//
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;
827
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
static void rekey(Key& k, const Key& newKey) { k = newKey; }
833
};
834
835
template <typename T>
836
struct JS_PUBLIC_API MovableCellHasher<JS::Heap<T>> {
837
using Key = JS::Heap<T>;
838
using Lookup = T;
839
840
static bool hasHash(const Lookup& l) {
841
return MovableCellHasher<T>::hasHash(l);
842
}
843
static bool ensureHash(const Lookup& l) {
844
return MovableCellHasher<T>::ensureHash(l);
845
}
846
static HashNumber hash(const Lookup& l) {
847
return MovableCellHasher<T>::hash(l);
848
}
849
static bool match(const Key& k, const Lookup& l) {
850
return MovableCellHasher<T>::match(k.unbarrieredGet(), l);
851
}
852
static void rekey(Key& k, const Key& newKey) { k.unsafeSet(newKey); }
853
};
854
855
} // namespace js
856
857
namespace mozilla {
858
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));
864
}
865
template <typename Lookup>
866
static bool ensureHash(Lookup&& l) {
867
return js::MovableCellHasher<T>::ensureHash(std::forward<Lookup>(l));
868
}
869
};
870
871
} // namespace mozilla
872
873
namespace js {
874
875
// The alignment must be set because the Rooted and PersistentRooted ptr fields
876
// may be accessed through reinterpret_cast<Rooted<ConcreteTraceable>*>, and
877
// the compiler may choose a different alignment for the ptr field when it
878
// knows the actual type stored in DispatchWrapper<T>.
879
//
880
// It would make more sense to align only those specific fields of type
881
// DispatchWrapper, rather than DispatchWrapper itself, but that causes MSVC to
882
// fail when Rooted is used in an IsConvertible test.
883
template <typename T>
884
class alignas(8) DispatchWrapper {
885
static_assert(JS::MapTypeToRootKind<T>::kind == JS::RootKind::Traceable,
886
"DispatchWrapper is intended only for usage with a Traceable");
887
888
using TraceFn = void (*)(JSTracer*, T*, const char*);
889
TraceFn tracer;
890
alignas(gc::CellAlignBytes) T storage;
891
892
public:
893
template <typename U>
894
MOZ_IMPLICIT DispatchWrapper(U&& initial)
895
: tracer(&JS::GCPolicy<T>::trace), storage(std::forward<U>(initial)) {}
896
897
// Mimic a pointer type, so that we can drop into Rooted.
898
T* operator&() { return &storage; }
899
const T* operator&() const { return &storage; }
900
operator T&() { return storage; }
901
operator const T&() const { return storage; }
902
903
// Trace the contained storage (of unknown type) using the trace function
904
// we set aside when we did know the type.
905
static void TraceWrapped(JSTracer* trc, T* thingp, const char* name) {
906
auto wrapper = reinterpret_cast<DispatchWrapper*>(
907
uintptr_t(thingp) - offsetof(DispatchWrapper, storage));
908
wrapper->tracer(trc, &wrapper->storage, name);
909
}
910
};
911
912
} /* namespace js */
913
914
namespace JS {
915
916
class JS_PUBLIC_API AutoGCRooter;
917
918
// Our instantiations of Rooted<void*> and PersistentRooted<void*> require an
919
// instantiation of MapTypeToRootKind.
920
template <>
921
struct MapTypeToRootKind<void*> {
922
static const RootKind kind = RootKind::Traceable;
923
};
924
925
using RootedListHeads =
926
mozilla::EnumeratedArray<RootKind, RootKind::Limit, Rooted<void*>*>;
927
928
// Superclass of JSContext which can be used for rooting data in use by the
929
// current thread but that does not provide all the functions of a JSContext.
930
class RootingContext {
931
// Stack GC roots for Rooted GC heap pointers.
932
RootedListHeads stackRoots_;
933
template <typename T>
934
friend class JS::Rooted;
935
936
// Stack GC roots for AutoFooRooter classes.
937
JS::AutoGCRooter* autoGCRooters_;
938
friend class JS::AutoGCRooter;
939
940
// Gecko profiling metadata.
941
// This isn't really rooting related. It's only here because we want
942
// GetContextProfilingStackIfEnabled to be inlineable into non-JS code, and
943
// we didn't want to add another superclass of JSContext just for this.
944
js::GeckoProfilerThread geckoProfiler_;
945
946
public:
947
RootingContext();
948
949
void traceStackRoots(JSTracer* trc);
950
void checkNoGCRooters();
951
952
js::GeckoProfilerThread& geckoProfiler() { return geckoProfiler_; }
953
954
protected:
955
// The remaining members in this class should only be accessed through
956
// JSContext pointers. They are unrelated to rooting and are in place so
957
// that inlined API functions can directly access the data.
958
959
/* The current realm. */
960
JS::Realm* realm_;
961
962
/* The current zone. */
963
JS::Zone* zone_;
964
965
public:
966
/* Limit pointer for checking native stack consumption. */
967
uintptr_t nativeStackLimit[StackKindCount];
968
969
static const RootingContext* get(const JSContext* cx) {
970
return reinterpret_cast<const RootingContext*>(cx);
971
}
972
973
static RootingContext* get(JSContext* cx) {
974
return reinterpret_cast<RootingContext*>(cx);
975
}
976
977
friend JS::Realm* js::GetContextRealm(const JSContext* cx);
978
friend JS::Zone* js::GetContextZone(const JSContext* cx);
979
};
980
981
class JS_PUBLIC_API AutoGCRooter {
982
protected:
983
enum class Tag : uint8_t {
984
Array, /* js::AutoArrayRooter */
985
ValueArray, /* js::AutoValueArray */
986
Parser, /* js::frontend::Parser */
987
BinASTParser, /* js::frontend::BinASTParser; only used if built with
988
* JS_BUILD_BINAST support */
989
WrapperVector, /* js::AutoWrapperVector */
990
Wrapper, /* js::AutoWrapperRooter */
991
Custom /* js::CustomAutoRooter */
992
};
993
994
public:
995
AutoGCRooter(JSContext* cx, Tag tag)
996
: AutoGCRooter(JS::RootingContext::get(cx), tag) {}
997
AutoGCRooter(JS::RootingContext* cx, Tag tag)
998
: down(cx->autoGCRooters_), stackTop(&cx->autoGCRooters_), tag_(tag) {
999
MOZ_ASSERT(this != *stackTop);
1000
*stackTop = this;
1001
}
1002
1003
~AutoGCRooter() {
1004
MOZ_ASSERT(this == *stackTop);
1005
*stackTop = down;
1006
}
1007
1008
/* Implemented in gc/RootMarking.cpp. */
1009
inline void trace(JSTracer* trc);
1010
static void traceAll(JSContext* cx, JSTracer* trc);
1011
static void traceAllWrappers(JSContext* cx, JSTracer* trc);
1012
1013
private:
1014
AutoGCRooter* const down;
1015
AutoGCRooter** const stackTop;
1016
1017
/*
1018
* Discriminates actual subclass of this being used. The meaning is
1019
* indicated by the corresponding value in the Tag enum.
1020
*/
1021
Tag tag_;
1022
1023
/* No copy or assignment semantics. */
1024
AutoGCRooter(AutoGCRooter& ida) = delete;
1025
void operator=(AutoGCRooter& ida) = delete;
1026
} JS_HAZ_ROOTED_BASE;
1027
1028
namespace detail {
1029
1030
/*
1031
* For pointer types, the TraceKind for tracing is based on the list it is
1032
* in (selected via MapTypeToRootKind), so no additional storage is
1033
* required here. Non-pointer types, however, share the same list, so the
1034
* function to call for tracing is stored adjacent to the struct. Since C++
1035
* cannot templatize on storage class, this is implemented via the wrapper
1036
* class DispatchWrapper.
1037
*/
1038
template <typename T>
1039
using MaybeWrapped =
1040
std::conditional_t<MapTypeToRootKind<T>::kind == JS::RootKind::Traceable,
1041
js::DispatchWrapper<T>, T>;
1042
1043
// Dummy types to make it easier to understand template overload preference
1044
// ordering.
1045
struct FallbackOverload {};
1046
struct PreferredOverload : FallbackOverload {};
1047
using OverloadSelector = PreferredOverload;
1048
1049
} /* namespace detail */
1050
1051
/**
1052
* Local variable of type T whose value is always rooted. This is typically
1053
* used for local variables, or for non-rooted values being passed to a
1054
* function that requires a handle, e.g. Foo(Root<T>(cx, x)).
1055
*
1056
* If you want to add additional methods to Rooted for a specific
1057
* specialization, define a RootedBase<T> specialization containing them.
1058
*/
1059
template <typename T>
1060
class MOZ_RAII Rooted : public js::RootedBase<T, Rooted<T>> {
1061
inline void registerWithRootLists(RootedListHeads& roots) {
1062
this->stack = &roots[JS::MapTypeToRootKind<T>::kind];
1063
this->prev = *stack;
1064
*stack = reinterpret_cast<Rooted<void*>*>(this);
1065
}
1066
1067
inline RootedListHeads& rootLists(RootingContext* cx) {
1068
return cx->stackRoots_;
1069
}
1070
inline RootedListHeads& rootLists(JSContext* cx) {
1071
return rootLists(RootingContext::get(cx));
1072
}
1073
1074
// Define either one or two Rooted(cx) constructors: the fallback one, which
1075
// constructs a Rooted holding a SafelyInitialized<T>, and a convenience one
1076
// for types that can be constructed with a cx, which will give a Rooted
1077
// holding a T(cx).
1078
1079
// Dummy type to distinguish these constructors from Rooted(cx, initial)
1080
struct CtorDispatcher {};
1081
1082
// Normal case: construct an empty Rooted holding a safely initialized but
1083
// empty T.
1084
template <typename RootingContext>
1085
Rooted(const RootingContext& cx, CtorDispatcher, detail::FallbackOverload)
1086
: Rooted(cx, SafelyInitialized<T>()) {}
1087
1088
// If T can be constructed with a cx, then define another constructor for it
1089
// that will be preferred.
1090
template <typename RootingContext,
1091
typename = typename std::enable_if<
1092
std::is_constructible<T, RootingContext>::value>::type>
1093
Rooted(const RootingContext& cx, CtorDispatcher, detail::PreferredOverload)
1094
: Rooted(cx, T(cx)) {}
1095
1096
public:
1097
using ElementType = T;
1098
1099
// Construct an empty Rooted. Delegates to an internal constructor that
1100
// chooses a specific meaning of "empty" depending on whether T can be
1101
// constructed with a cx.
1102
template <typename RootingContext>
1103
explicit Rooted(const RootingContext& cx)
1104
: Rooted(cx, CtorDispatcher(), detail::OverloadSelector()) {}
1105
1106
template <typename RootingContext, typename S>
1107
Rooted(const RootingContext& cx, S&& initial)
1108
: ptr(std::forward<S>(initial)) {
1109
MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1110
registerWithRootLists(rootLists(cx));
1111
}
1112
1113
~Rooted() {
1114
MOZ_ASSERT(*stack == reinterpret_cast<Rooted<void*>*>(this));
1115
*stack = prev;
1116
}
1117
1118
Rooted<T>* previous() { return reinterpret_cast<Rooted<T>*>(prev); }
1119
1120
/*
1121
* This method is public for Rooted so that Codegen.py can use a Rooted
1122
* interchangeably with a MutableHandleValue.
1123
*/
1124
void set(const T& value) {
1125
ptr = value;
1126
MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1127
}
1128
void set(T&& value) {
1129
ptr = std::move(value);
1130
MOZ_ASSERT(GCPolicy<T>::isValid(ptr));
1131
}
1132
1133
DECLARE_POINTER_CONSTREF_OPS(T);
1134
DECLARE_POINTER_ASSIGN_OPS(Rooted, T);
1135
DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr);
1136
DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS(ptr);
1137
1138
private:
1139
/*
1140
* These need to be templated on void* to avoid aliasing issues between, for
1141
* example, Rooted<JSObject> and Rooted<JSFunction>, which use the same
1142
* stack head pointer for different classes.
1143
*/
1144
Rooted<void*>** stack;
1145
Rooted<void*>* prev;
1146
1147
detail::MaybeWrapped<T> ptr;
1148
1149
Rooted(const Rooted&) = delete;
1150
} JS_HAZ_ROOTED;
1151
1152
namespace detail {
1153
1154
template <typename T>
1155
struct DefineComparisonOps<Rooted<T>> : std::true_type {
1156
static const T& get(const Rooted<T>& v) { return v.get(); }
1157
};
1158
1159
} // namespace detail
1160
1161
} /* namespace JS */
1162
1163
namespace js {
1164
1165
/*
1166
* Inlinable accessors for JSContext.
1167
*
1168
* - These must not be available on the more restricted superclasses of
1169
* JSContext, so we can't simply define them on RootingContext.
1170
*
1171
* - They're perfectly ordinary JSContext functionality, so ought to be
1172
* usable without resorting to jsfriendapi.h, and when JSContext is an
1173
* incomplete type.
1174
*/
1175
inline JS::Realm* GetContextRealm(const JSContext* cx) {
1176
return JS::RootingContext::get(cx)->realm_;
1177
}
1178
1179
inline JS::Compartment* GetContextCompartment(const JSContext* cx) {
1180
if (JS::Realm* realm = GetContextRealm(cx)) {
1181
return GetCompartmentForRealm(realm);
1182
}
1183
return nullptr;
1184
}
1185
1186
inline JS::Zone* GetContextZone(const JSContext* cx) {
1187
return JS::RootingContext::get(cx)->zone_;
1188
}
1189
1190
inline ProfilingStack* GetContextProfilingStackIfEnabled(JSContext* cx) {
1191
return JS::RootingContext::get(cx)
1192
->geckoProfiler()
1193
.getProfilingStackIfEnabled();
1194
}
1195
1196
/**
1197
* Augment the generic Rooted<T> interface when T = JSObject* with
1198
* class-querying and downcasting operations.
1199
*
1200
* Given a Rooted<JSObject*> obj, one can view
1201
* Handle<StringObject*> h = obj.as<StringObject*>();
1202
* as an optimization of
1203
* Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
1204
* Handle<StringObject*> h = rooted;
1205
*/
1206
template <typename Container>
1207
class RootedBase<JSObject*, Container>
1208
: public MutableWrappedPtrOperations<JSObject*, Container> {
1209
public:
1210
template <class U>
1211
JS::Handle<U*> as() const;
1212
};
1213
1214
/**
1215
* Augment the generic Handle<T> interface when T = JSObject* with
1216
* downcasting operations.
1217
*
1218
* Given a Handle<JSObject*> obj, one can view
1219
* Handle<StringObject*> h = obj.as<StringObject*>();
1220
* as an optimization of
1221
* Rooted<StringObject*> rooted(cx, &obj->as<StringObject*>());
1222
* Handle<StringObject*> h = rooted;
1223
*/
1224
template <typename Container>
1225
class HandleBase<JSObject*, Container>
1226
: public WrappedPtrOperations<JSObject*, Container> {
1227
public:
1228
template <class U>
1229
JS::Handle<U*> as() const;
1230
};
1231
1232
} /* namespace js */
1233
1234
namespace JS {
1235
1236
template <typename T>
1237
template <typename S>
1238
inline Handle<T>::Handle(
1239
const Rooted<S>& root,
1240
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1241
ptr = reinterpret_cast<const T*>(root.address());
1242
}
1243
1244
template <typename T>
1245
template <typename S>
1246
inline Handle<T>::Handle(
1247
const PersistentRooted<S>& root,
1248
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1249
ptr = reinterpret_cast<const T*>(root.address());
1250
}
1251
1252
template <typename T>
1253
template <typename S>
1254
inline Handle<T>::Handle(
1255
MutableHandle<S>& root,
1256
std::enable_if_t<std::is_convertible_v<S, T>, int> dummy) {
1257
ptr = reinterpret_cast<const T*>(root.address());
1258
}
1259
1260
template <typename T>
1261
inline MutableHandle<T>::MutableHandle(Rooted<T>* root) {
1262
static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1263
"MutableHandle must be binary compatible with T*.");
1264
ptr = root->address();
1265
}
1266
1267
template <typename T>
1268
inline MutableHandle<T>::MutableHandle(PersistentRooted<T>* root) {
1269
static_assert(sizeof(MutableHandle<T>) == sizeof(T*),
1270
"MutableHandle must be binary compatible with T*.");
1271
ptr = root->address();
1272
}
1273
1274
JS_PUBLIC_API void AddPersistentRoot(RootingContext* cx, RootKind kind,
1275
PersistentRooted<void*>* root);
1276
1277
JS_PUBLIC_API void AddPersistentRoot(JSRuntime* rt, RootKind kind,
1278
PersistentRooted<void*>* root);
1279
1280
/**
1281
* A copyable, assignable global GC root type with arbitrary lifetime, an
1282
* infallible constructor, and automatic unrooting on destruction.
1283
*
1284
* These roots can be used in heap-allocated data structures, so they are not
1285
* associated with any particular JSContext or stack. They are registered with
1286
* the JSRuntime itself, without locking. Initialization may take place on
1287
* construction, or in two phases if the no-argument constructor is called
1288
* followed by init().
1289
*
1290
* Note that you must not use an PersistentRooted in an object owned by a JS
1291
* object:
1292
*
1293
* Whenever one object whose lifetime is decided by the GC refers to another
1294
* such object, that edge must be traced only if the owning JS object is traced.
1295
* This applies not only to JS objects (which obviously are managed by the GC)
1296
* but also to C++ objects owned by JS objects.
1297
*
1298
* If you put a PersistentRooted in such a C++ object, that is almost certainly
1299
* a leak. When a GC begins, the referent of the PersistentRooted is treated as
1300
* live, unconditionally (because a PersistentRooted is a *root*), even if the
1301
* JS object that owns it is unreachable. If there is any path from that
1302
* referent back to the JS object, then the C++ object containing the
1303
* PersistentRooted will not be destructed, and the whole blob of objects will
1304
* not be freed, even if there are no references to them from the outside.
1305
*
1306
* In the context of Firefox, this is a severe restriction: almost everything in
1307
* Firefox is owned by some JS object or another, so using PersistentRooted in
1308
* such objects would introduce leaks. For these kinds of edges, Heap<T> or
1309
* TenuredHeap<T> would be better types. It's up to the implementor of the type
1310
* containing Heap<T> or TenuredHeap<T> members to make sure their referents get
1311
* marked when the object itself is marked.
1312
*/
1313
template <typename T>
1314
class PersistentRooted
1315
: public js::RootedBase<T, PersistentRooted<T>>,
1316
private mozilla::LinkedListElement<PersistentRooted<T>> {
1317
using ListBase = mozilla::LinkedListElement<PersistentRooted<T>>;
1318
1319
friend class mozilla::LinkedList<PersistentRooted>;
1320
friend class mozilla::LinkedListElement<PersistentRooted>;
1321
1322
void registerWithRootLists(RootingContext* cx) {
1323
MOZ_ASSERT(!initialized());
1324
JS::RootKind kind = JS::MapTypeToRootKind<T>::kind;
1325
AddPersistentRoot(cx, kind,
1326
reinterpret_cast<JS::PersistentRooted<void*>*>(this));
1327
}
1328
1329
void registerWithRootLists(JSRuntime* rt) {
1330
MOZ_ASSERT(!initialized());
1331
JS::RootKind kind = JS::MapTypeToRootKind<T>::kind;
1332
AddPersistentRoot(rt, kind,
1333
reinterpret_cast<JS::PersistentRooted<void*>*>(this));
1334
}
1335
1336
public:
1337
using ElementType = T;
1338
1339
PersistentRooted() : ptr(SafelyInitialized<T>()) {}
1340
1341
explicit PersistentRooted(RootingContext* cx) : ptr(SafelyInitialized<T>()) {
1342
registerWithRootLists(cx);
1343
}
1344
1345
explicit PersistentRooted(JSContext* cx) : ptr(SafelyInitialized<T>()) {
1346
registerWithRootLists(RootingContext::get(cx));
1347
}
1348
1349
template <typename U>
1350
PersistentRooted(RootingContext* cx, U&& initial)
1351
: ptr(std::forward<U>(initial)) {
1352
registerWithRootLists(cx);
1353
}
1354
1355
template <typename U>
1356
PersistentRooted(JSContext* cx, U&& initial) : ptr(std::forward<U>(initial)) {
1357
registerWithRootLists(RootingContext::get(cx));
1358
}
1359
1360
explicit PersistentRooted(JSRuntime* rt) : ptr(SafelyInitialized<T>()) {
1361
registerWithRootLists(rt);
1362
}
1363
1364
template <typename U>
1365
PersistentRooted(JSRuntime* rt, U&& initial) : ptr(std::forward<U>(initial)) {
1366
registerWithRootLists(rt);
1367
}
1368
1369
PersistentRooted(const PersistentRooted& rhs)
1370
: mozilla::LinkedListElement<PersistentRooted<T>>(), ptr(rhs.ptr) {
1371
/*
1372
* Copy construction takes advantage of the fact that the original
1373
* is already inserted, and simply adds itself to whatever list the
1374
* original was on - no JSRuntime pointer needed.
1375
*
1376
* This requires mutating rhs's links, but those should be 'mutable'
1377
* anyway. C++ doesn't let us declare mutable base classes.
1378
*/
1379
const_cast<PersistentRooted&>(rhs).setNext(this);
1380
}
1381
1382
bool initialized() { return ListBase::isInList(); }
1383
1384
void init(RootingContext* cx) { init(cx, SafelyInitialized<T>()); }
1385
void init(JSContext* cx) { init(RootingContext::get(cx)); }
1386
1387
template <typename U>
1388
void init(RootingContext* cx, U&& initial) {
1389
ptr = std::forward<U>(initial);
1390
registerWithRootLists(cx);
1391
}
1392
template <typename U>
1393
void init(JSContext* cx, U&& initial) {
1394
ptr = std::forward<U>(initial);
1395
registerWithRootLists(RootingContext::get(cx));
1396
}
1397
1398
void reset() {
1399
if (initialized()) {
1400
set(SafelyInitialized<T>());
1401
ListBase::remove();
1402
}
1403
}
1404
1405
DECLARE_POINTER_CONSTREF_OPS(T);
1406
DECLARE_POINTER_ASSIGN_OPS(PersistentRooted, T);
1407
DECLARE_NONPOINTER_ACCESSOR_METHODS(ptr);
1408
1409
// These are the same as DECLARE_NONPOINTER_MUTABLE_ACCESSOR_METHODS, except
1410
// they check that |this| is initialized in case the caller later stores
1411
// something in |ptr|.
1412
T* address() {
1413
MOZ_ASSERT(initialized());
1414
return &ptr;
1415
}
1416
T& get() {
1417
MOZ_ASSERT(initialized());
1418
return ptr;
1419
}
1420
1421
template <typename U>
1422
void set(U&& value) {
1423
MOZ_ASSERT(initialized());
1424
ptr = std::forward<U>(value);
1425
}
1426
1427
private:
1428
detail::MaybeWrapped<T> ptr;
1429
} JS_HAZ_ROOTED;
1430
1431
namespace detail {
1432
1433
template <typename T>
1434
struct DefineComparisonOps<PersistentRooted<T>> : std::true_type {
1435
static const T& get(const PersistentRooted<T>& v) { return v.get(); }
1436
};
1437
1438
} // namespace detail
1439
1440
} /* namespace JS */
1441
1442
namespace js {
1443
1444
template <typename T, typename D, typename Container>
1445
class WrappedPtrOperations<UniquePtr<T, D>, Container> {
1446
const UniquePtr<T, D>& uniquePtr() const {
1447
return static_cast<const Container*>(this)->get();
1448
}
1449
1450
public:
1451
explicit operator bool() const { return !!uniquePtr(); }
1452
T* get() const { return uniquePtr().get(); }
1453
T* operator->() const { return get(); }
1454
T& operator*() const { return *uniquePtr(); }
1455
};
1456
1457
template <typename T, typename D, typename Container>
1458
class MutableWrappedPtrOperations<UniquePtr<T, D>, Container>
1459
: public WrappedPtrOperations<UniquePtr<T, D>, Container> {
1460
UniquePtr<T, D>& uniquePtr() { return static_cast<Container*>(this)->get(); }
1461
1462
public:
1463
MOZ_MUST_USE typename UniquePtr<T, D>::Pointer release() {
1464
return uniquePtr().release();
1465
}
1466
void reset(T* ptr = T()) { uniquePtr().reset(ptr); }
1467
};
1468
1469
namespace gc {
1470
1471
template <typename T, typename TraceCallbacks>
1472
void CallTraceCallbackOnNonHeap(T* v, const TraceCallbacks& aCallbacks,
1473
const char* aName, void* aClosure) {
1474
static_assert(sizeof(T) == sizeof(JS::Heap<T>),
1475
"T and Heap<T> must be compatible.");
1476
MOZ_ASSERT(v);
1477
mozilla::DebugOnly<Cell*> cell = BarrierMethods<T>::asGCThingOrNull(*v);
1478
MOZ_ASSERT(cell);
1479
MOZ_ASSERT(!IsInsideNursery(cell));
1480
JS::Heap<T>* asHeapT = reinterpret_cast<JS::Heap<T>*>(v);
1481
aCallbacks.Trace(asHeapT, aName, aClosure);
1482
}
1483
1484
} /* namespace gc */
1485
1486
} /* namespace js */
1487
1488
#endif /* js_RootingAPI_h */