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