forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RefPtr.h
530 lines (449 loc) · 13.1 KB
/
RefPtr.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/* Helpers for defining and using refcounted objects. */
#ifndef mozilla_RefPtr_h
#define mozilla_RefPtr_h
#include "mozilla/Assertions.h"
#include "mozilla/Atomics.h"
#include "mozilla/Attributes.h"
#include "mozilla/RefCountType.h"
#include "mozilla/TypeTraits.h"
#if defined(MOZILLA_INTERNAL_API)
#include "nsXPCOM.h"
#endif
#if defined(MOZILLA_INTERNAL_API) && (defined(DEBUG) || defined(FORCE_BUILD_REFCNT_LOGGING))
#define MOZ_REFCOUNTED_LEAK_CHECKING
#endif
namespace mozilla {
template<typename T> class RefCounted;
template<typename T> class RefPtr;
template<typename T> class TemporaryRef;
template<typename T> class OutParamRef;
template<typename T> OutParamRef<T> byRef(RefPtr<T>&);
/**
* RefCounted<T> is a sort of a "mixin" for a class T. RefCounted
* manages, well, refcounting for T, and because RefCounted is
* parameterized on T, RefCounted<T> can call T's destructor directly.
* This means T doesn't need to have a virtual dtor and so doesn't
* need a vtable.
*
* RefCounted<T> is created with refcount == 0. Newly-allocated
* RefCounted<T> must immediately be assigned to a RefPtr to make the
* refcount > 0. It's an error to allocate and free a bare
* RefCounted<T>, i.e. outside of the RefPtr machinery. Attempts to
* do so will abort DEBUG builds.
*
* Live RefCounted<T> have refcount > 0. The lifetime (refcounts) of
* live RefCounted<T> are controlled by RefPtr<T> and
* RefPtr<super/subclass of T>. Upon a transition from refcounted==1
* to 0, the RefCounted<T> "dies" and is destroyed. The "destroyed"
* state is represented in DEBUG builds by refcount==0xffffdead. This
* state distinguishes use-before-ref (refcount==0) from
* use-after-destroy (refcount==0xffffdead).
*
* Note that when deriving from RefCounted or AtomicRefCounted, you
* should add MOZ_DECLARE_REFCOUNTED_TYPENAME(ClassName) to the public
* section of your class, where ClassName is the name of your class.
*/
namespace detail {
#ifdef DEBUG
const MozRefCountType DEAD = 0xffffdead;
#endif
// When building code that gets compiled into Gecko, try to use the
// trace-refcount leak logging facilities.
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING
class RefCountLogger
{
public:
static void logAddRef(const void* aPointer, MozRefCountType aRefCount,
const char* aTypeName, uint32_t aInstanceSize)
{
MOZ_ASSERT(aRefCount != DEAD);
NS_LogAddRef(const_cast<void*>(aPointer), aRefCount, aTypeName, aInstanceSize);
}
static void logRelease(const void* aPointer, MozRefCountType aRefCount,
const char* aTypeName)
{
MOZ_ASSERT(aRefCount != DEAD);
NS_LogRelease(const_cast<void*>(aPointer), aRefCount, aTypeName);
}
};
#endif
// This is used WeakPtr.h as well as this file.
enum RefCountAtomicity
{
AtomicRefCount,
NonAtomicRefCount
};
template<typename T, RefCountAtomicity Atomicity>
class RefCounted
{
friend class RefPtr<T>;
protected:
RefCounted() : refCnt(0) { }
~RefCounted() {
MOZ_ASSERT(refCnt == detail::DEAD);
}
public:
// Compatibility with nsRefPtr.
void AddRef() const {
// Note: this method must be thread safe for AtomicRefCounted.
MOZ_ASSERT(int32_t(refCnt) >= 0);
#ifndef MOZ_REFCOUNTED_LEAK_CHECKING
++refCnt;
#else
const char* type = static_cast<const T*>(this)->typeName();
uint32_t size = static_cast<const T*>(this)->typeSize();
const void* ptr = static_cast<const T*>(this);
MozRefCountType cnt = ++refCnt;
detail::RefCountLogger::logAddRef(ptr, cnt, type, size);
#endif
}
void Release() const {
// Note: this method must be thread safe for AtomicRefCounted.
MOZ_ASSERT(int32_t(refCnt) > 0);
#ifndef MOZ_REFCOUNTED_LEAK_CHECKING
MozRefCountType cnt = --refCnt;
#else
const char* type = static_cast<const T*>(this)->typeName();
const void* ptr = static_cast<const T*>(this);
MozRefCountType cnt = --refCnt;
// Note: it's not safe to touch |this| after decrementing the refcount,
// except for below.
detail::RefCountLogger::logRelease(ptr, cnt, type);
#endif
if (0 == cnt) {
// Because we have atomically decremented the refcount above, only
// one thread can get a 0 count here, so as long as we can assume that
// everything else in the system is accessing this object through
// RefPtrs, it's safe to access |this| here.
#ifdef DEBUG
refCnt = detail::DEAD;
#endif
delete static_cast<const T*>(this);
}
}
// Compatibility with wtf::RefPtr.
void ref() { AddRef(); }
void deref() { Release(); }
MozRefCountType refCount() const { return refCnt; }
bool hasOneRef() const {
MOZ_ASSERT(refCnt > 0);
return refCnt == 1;
}
private:
mutable typename Conditional<Atomicity == AtomicRefCount, Atomic<MozRefCountType>, MozRefCountType>::Type refCnt;
};
#ifdef MOZ_REFCOUNTED_LEAK_CHECKING
#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T) \
virtual const char* typeName() const { return #T; } \
virtual size_t typeSize() const { return sizeof(*this); }
#else
#define MOZ_DECLARE_REFCOUNTED_VIRTUAL_TYPENAME(T)
#endif
// Note that this macro is expanded unconditionally because it declares only
// two small inline functions which will hopefully get eliminated by the linker
// in non-leak-checking builds.
#define MOZ_DECLARE_REFCOUNTED_TYPENAME(T) \
const char* typeName() const { return #T; } \
size_t typeSize() const { return sizeof(*this); }
}
template<typename T>
class RefCounted : public detail::RefCounted<T, detail::NonAtomicRefCount>
{
public:
~RefCounted() {
static_assert(IsBaseOf<RefCounted, T>::value,
"T must derive from RefCounted<T>");
}
};
namespace external {
/**
* AtomicRefCounted<T> is like RefCounted<T>, with an atomically updated
* reference counter.
*
* NOTE: Please do not use this class, use NS_INLINE_DECL_THREADSAFE_REFCOUNTING
* instead.
*/
template<typename T>
class AtomicRefCounted : public mozilla::detail::RefCounted<T, mozilla::detail::AtomicRefCount>
{
public:
~AtomicRefCounted() {
static_assert(IsBaseOf<AtomicRefCounted, T>::value,
"T must derive from AtomicRefCounted<T>");
}
};
}
/**
* RefPtr points to a refcounted thing that has AddRef and Release
* methods to increase/decrease the refcount, respectively. After a
* RefPtr<T> is assigned a T*, the T* can be used through the RefPtr
* as if it were a T*.
*
* A RefPtr can forget its underlying T*, which results in the T*
* being wrapped in a temporary object until the T* is either
* re-adopted from or released by the temporary.
*/
template<typename T>
class RefPtr
{
// To allow them to use unref()
friend class TemporaryRef<T>;
friend class OutParamRef<T>;
struct DontRef {};
public:
RefPtr() : ptr(0) { }
RefPtr(const RefPtr& o) : ptr(ref(o.ptr)) {}
MOZ_IMPLICIT RefPtr(const TemporaryRef<T>& o) : ptr(o.drop()) {}
MOZ_IMPLICIT RefPtr(T* t) : ptr(ref(t)) {}
template<typename U>
RefPtr(const RefPtr<U>& o) : ptr(ref(o.get())) {}
~RefPtr() { unref(ptr); }
RefPtr& operator=(const RefPtr& o) {
assign(ref(o.ptr));
return *this;
}
RefPtr& operator=(const TemporaryRef<T>& o) {
assign(o.drop());
return *this;
}
RefPtr& operator=(T* t) {
assign(ref(t));
return *this;
}
template<typename U>
RefPtr& operator=(const RefPtr<U>& o) {
assign(ref(o.get()));
return *this;
}
TemporaryRef<T> forget() {
T* tmp = ptr;
ptr = 0;
return TemporaryRef<T>(tmp, DontRef());
}
T* get() const { return ptr; }
operator T*() const { return ptr; }
T* operator->() const { return ptr; }
T& operator*() const { return *ptr; }
template<typename U>
operator TemporaryRef<U>() { return TemporaryRef<U>(ptr); }
private:
void assign(T* t) {
unref(ptr);
ptr = t;
}
T* ptr;
static MOZ_ALWAYS_INLINE T* ref(T* t) {
if (t)
t->AddRef();
return t;
}
static MOZ_ALWAYS_INLINE void unref(T* t) {
if (t)
t->Release();
}
};
/**
* TemporaryRef<T> represents an object that holds a temporary
* reference to a T. TemporaryRef objects can't be manually ref'd or
* unref'd (being temporaries, not lvalues), so can only relinquish
* references to other objects, or unref on destruction.
*/
template<typename T>
class TemporaryRef
{
// To allow it to construct TemporaryRef from a bare T*
friend class RefPtr<T>;
typedef typename RefPtr<T>::DontRef DontRef;
public:
MOZ_IMPLICIT TemporaryRef(T* t) : ptr(RefPtr<T>::ref(t)) {}
TemporaryRef(const TemporaryRef& o) : ptr(o.drop()) {}
template<typename U>
TemporaryRef(const TemporaryRef<U>& o) : ptr(o.drop()) {}
~TemporaryRef() { RefPtr<T>::unref(ptr); }
T* drop() const {
T* tmp = ptr;
ptr = 0;
return tmp;
}
private:
TemporaryRef(T* t, const DontRef&) : ptr(t) {}
mutable T* ptr;
TemporaryRef() MOZ_DELETE;
void operator=(const TemporaryRef&) MOZ_DELETE;
};
/**
* OutParamRef is a wrapper that tracks a refcounted pointer passed as
* an outparam argument to a function. OutParamRef implements COM T**
* outparam semantics: this requires the callee to AddRef() the T*
* returned through the T** outparam on behalf of the caller. This
* means the caller (through OutParamRef) must Release() the old
* object contained in the tracked RefPtr. It's OK if the callee
* returns the same T* passed to it through the T** outparam, as long
* as the callee obeys the COM discipline.
*
* Prefer returning TemporaryRef<T> from functions over creating T**
* outparams and passing OutParamRef<T> to T**. Prefer RefPtr<T>*
* outparams over T** outparams.
*/
template<typename T>
class OutParamRef
{
friend OutParamRef byRef<T>(RefPtr<T>&);
public:
~OutParamRef() {
RefPtr<T>::unref(refPtr.ptr);
refPtr.ptr = tmp;
}
operator T**() { return &tmp; }
private:
explicit OutParamRef(RefPtr<T>& p) : refPtr(p), tmp(p.get()) {}
RefPtr<T>& refPtr;
T* tmp;
OutParamRef() MOZ_DELETE;
OutParamRef& operator=(const OutParamRef&) MOZ_DELETE;
};
/**
* byRef cooperates with OutParamRef to implement COM outparam semantics.
*/
template<typename T>
OutParamRef<T>
byRef(RefPtr<T>& ptr)
{
return OutParamRef<T>(ptr);
}
} // namespace mozilla
#if 0
// Command line that builds these tests
//
// cp RefPtr.h test.cc && g++ -g -Wall -pedantic -DDEBUG -o test test.cc && ./test
using namespace mozilla;
struct Foo : public RefCounted<Foo>
{
MOZ_DECLARE_REFCOUNTED_TYPENAME(Foo)
Foo() : dead(false) { }
~Foo() {
MOZ_ASSERT(!dead);
dead = true;
numDestroyed++;
}
bool dead;
static int numDestroyed;
};
int Foo::numDestroyed;
struct Bar : public Foo { };
TemporaryRef<Foo>
NewFoo()
{
return RefPtr<Foo>(new Foo());
}
TemporaryRef<Foo>
NewBar()
{
return new Bar();
}
void
GetNewFoo(Foo** f)
{
*f = new Bar();
// Kids, don't try this at home
(*f)->AddRef();
}
void
GetPassedFoo(Foo** f)
{
// Kids, don't try this at home
(*f)->AddRef();
}
void
GetNewFoo(RefPtr<Foo>* f)
{
*f = new Bar();
}
void
GetPassedFoo(RefPtr<Foo>* f)
{}
TemporaryRef<Foo>
GetNullFoo()
{
return 0;
}
int
main(int argc, char** argv)
{
// This should blow up
// Foo* f = new Foo(); delete f;
MOZ_ASSERT(0 == Foo::numDestroyed);
{
RefPtr<Foo> f = new Foo();
MOZ_ASSERT(f->refCount() == 1);
}
MOZ_ASSERT(1 == Foo::numDestroyed);
{
RefPtr<Foo> f1 = NewFoo();
RefPtr<Foo> f2(NewFoo());
MOZ_ASSERT(1 == Foo::numDestroyed);
}
MOZ_ASSERT(3 == Foo::numDestroyed);
{
RefPtr<Foo> b = NewBar();
MOZ_ASSERT(3 == Foo::numDestroyed);
}
MOZ_ASSERT(4 == Foo::numDestroyed);
{
RefPtr<Foo> f1;
{
f1 = new Foo();
RefPtr<Foo> f2(f1);
RefPtr<Foo> f3 = f2;
MOZ_ASSERT(4 == Foo::numDestroyed);
}
MOZ_ASSERT(4 == Foo::numDestroyed);
}
MOZ_ASSERT(5 == Foo::numDestroyed);
{
RefPtr<Foo> f = new Foo();
f.forget();
MOZ_ASSERT(6 == Foo::numDestroyed);
}
{
RefPtr<Foo> f = new Foo();
GetNewFoo(byRef(f));
MOZ_ASSERT(7 == Foo::numDestroyed);
}
MOZ_ASSERT(8 == Foo::numDestroyed);
{
RefPtr<Foo> f = new Foo();
GetPassedFoo(byRef(f));
MOZ_ASSERT(8 == Foo::numDestroyed);
}
MOZ_ASSERT(9 == Foo::numDestroyed);
{
RefPtr<Foo> f = new Foo();
GetNewFoo(&f);
MOZ_ASSERT(10 == Foo::numDestroyed);
}
MOZ_ASSERT(11 == Foo::numDestroyed);
{
RefPtr<Foo> f = new Foo();
GetPassedFoo(&f);
MOZ_ASSERT(11 == Foo::numDestroyed);
}
MOZ_ASSERT(12 == Foo::numDestroyed);
{
RefPtr<Foo> f1 = new Bar();
}
MOZ_ASSERT(13 == Foo::numDestroyed);
{
RefPtr<Foo> f = GetNullFoo();
MOZ_ASSERT(13 == Foo::numDestroyed);
}
MOZ_ASSERT(13 == Foo::numDestroyed);
return 0;
}
#endif
#endif /* mozilla_RefPtr_h */