File: refcnt.h

package info (click to toggle)
sfs 1%3A0.5k-8
  • links: PTS
  • area: main
  • in suites: woody
  • size: 5,388 kB
  • ctags: 8,556
  • sloc: cpp: 43,410; ansic: 17,574; sh: 8,412; makefile: 771; yacc: 277; lex: 96; sed: 47
file content (499 lines) | stat: -rw-r--r-- 16,812 bytes parent folder | download
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
// -*-c++-*-
/* $Id: refcnt.h,v 1.14 2001/06/26 04:04:32 dm Exp $ */

/*
 *
 * Copyright (C) 1998 David Mazieres (dm@uun.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 */

/* This is a simple reference counted garbage collector.  The usage is
 * as follows:
 *
 *   class foo : public bar { ... };
 *
 *      ...
 *      ref<foo> f = new refcounted<foo> ( ... );
 *      ptr<bar> b = f;
 *      f = new refcounted<foo> ( ... );
 *      b = NULL;
 *
 * A refcounted<foo> takes the same constructor arguments as foo,
 * except that constructors with more than 7 arguments cannot be
 * called.  (This is because there are no varargs templates.  You can
 * raise the limit from 7 to an arbitrary number if you wish, however,
 * by editting vatmpl.h.)
 *
 * A ptr<foo> behaves like a foo *, except that it is reference
 * counted.  The foo will be deleted when all pointers go away.  Also,
 * array subscripts will not work on a ptr<foo>.  You can only
 * allocate one reference counted object at a time.
 *
 * A ref<foo> is like a ptr<foo>, except that a ref<foo> can never be
 * NULL.  If you try to assign a NULL ptr<foo> to a ref<foo> you will
 * get an immediate core dump.  The statement "ref<foo> = NULL" will
 * generate a compile time error.
 *
 * A "const ref<foo>" cannot change what it is pointing to, but the
 * foo pointed to can be modified.  A "ref <const foo>" points to a
 * foo you cannot change.  A ref<foo> can be converted to a ref<const
 * foo>.  In general, you can implicitly convert a ref<A> to a ref<B>
 * if you can implicitly convert an A* to a B*.
 *
 * You can also implicitly convert a ref<foo> or ptr<foo> to a foo *.
 * Many functions can get away with taking a foo * instead of a
 * ptr<foo> if they don't eliminate any existing references (or the
 * foo's address around after returning).
 *
 * On both the Pentium and Pentium Pro, a function taking a ref<foo>
 * argument usually seems to take 10-15 more cycles the same function
 * with a foo * argument.  With some versions of g++, though, this
 * number can go as high as 50 cycles unless you compile with
 * '-fno-exceptions'.
 *
 * Sometimes you want to do something other than simply free an object
 * when its reference count goes to 0.  This can usually be
 * accomplished by the reference counted object's destructor.
 * However, after a destructor is run, the memory associated with an
 * object is freed.  If you don't want the object to be deleted, you
 * can define a finalize method that gets invoked once the reference
 * count goes to 0.  Any class with a finalize method must declare a
 * virtual base class of refcount.  For example:
 *
 *   class foo : public virtual refcount {
 *     ...
 *     void finalize () { recycle (this); }
 *   };
 *
 * Occasionally you may want to generate a reference counted ref or
 * ptr from an ordinary pointer.  This might, for instance, be used by
 * the recycle function above.
 *
 * You can do this with the function mkref, but again only if the
 * underlying type has a virtual base class of refcount.  Given the
 * above definition, recycle might do this:
 *
 *   void
 *   recycle (foo *fp)
 *   {
 *     ref<foo> = mkref (fp);
 *     ...
 *   }
 *
 * Note that unlike in Java, an objects finalize method will be called
 * every time the reference count reaches 0, not just the first time.
 * Thus, there is nothing morally wrong with "resurrecting" objects as
 * they are being garbage collected.
 *
 * Use of mkref is potentially dangerous, however.  You can disallow
 * its use on a per-class basis by simply not giving your object a
 * public virtual base class of refcount.
 *
 *   class foo {
 *     // fine, no mkref or finalize allowed
 *   };
 *
 *   class foo : private virtual refcount {
 *     void finalize () { ... }
 *     // finalize will work, but not mkref
 *   };
 *
 * If you like to live dangerously, there are a few more things you
 * can do (but probably shouldn't).  You can keep the original
 * "refcounted<foo> *" around and use it to generate more references
 * from a finalize method (or elsewhere).  If foo has a virtual base
 * class of refcount, it will also inherit the methods refcount_inc()
 * and refcount_dec().  You can use these to create memory leaks and
 * crash your program, respectively.
 */

#ifndef _REFCNT_H_INCLUDED_
#define _REFCNT_H_INCLUDED_ 1

#if VERBOSE_REFCNT
#include <typeinfo>
void refcnt_warn (const char *op, const type_info &type, void *addr, int cnt);
#endif /* VERBOSE_REFCNT */

#include "opnew.h"
#include "vatmpl.h"

class __globaldestruction_t {
  static bool started;
public:
  ~__globaldestruction_t () { started = true; }
  operator bool () { return started; }
};
static __globaldestruction_t globaldestruction;
/* The following is for the end of files that use bssptr's */
#define GLOBALDESTRUCT static __globaldestruction_t __gd__ ## __LINE__

template<class T> class ref;
template<class T> class ptr;
enum reftype { scalar, vsize };
template<class T, reftype = scalar> class refcounted;
template<class T> ref<T> mkref (T *);

class refcount {
  u_int refcount_cnt;
  virtual void refcount_call_finalize () = 0;
  friend class refpriv;
protected:
  refcount () : refcount_cnt (0) {}
  virtual ~refcount () {}
  void finalize () { delete this; }
  void refcount_inc () {
#if VERBOSE_REFCNT
    refcnt_warn ("INC", typeid (*this), this, refcount_cnt + 1);
#endif /* VERBOSE_REFCNT */
    refcount_cnt++;
  }
  void refcount_dec () {
#if VERBOSE_REFCNT
    refcnt_warn ("DEC", typeid (*this), this, refcount_cnt - 1);
#endif /* VERBOSE_REFCNT */
    if (!--refcount_cnt)
      refcount_call_finalize ();
  }
  u_int refcount_getcnt () { return refcount_cnt; }
};

class refpriv {
protected:
  /* We introduce a private type "privtype," that users won't have
   * floating around.  The idea is that NULL can implicitly be
   * converted to a privtype *.  Thus, when passing NULL as an
   * argument to a function taking a ptr<T>, a null ptr will be
   * constructed.  Likewise, if f is of type ptr<T>, the assignment f
   * = NULL will make f null.  By omitting this from ref, we can
   * ensure that ref<foo> f = NULL results in a compile-time error. */
  class privtype {};

private:
#ifndef NO_TEMPLATE_FRIENDS
  template<class U> friend class ref;
  template<class U> friend class ptr;
#else /* NO_TEMPLATE_FRIENDS */
protected:
#endif /* NO_TEMPLATE_FRIENDS */

  static void rdec (refcount *c) { c->refcount_dec (); }
  static void rinc (refcount *c) { c->refcount_inc (); }
  template<class T> static void rinc (const ::ref<T> &r) { r.inc (); }
  template<class T> static void rinc (const ::ptr<T> &r) { r.inc (); }
  template<class T, reftype v> static void rinc (refcounted<T, v> *pp)
    { pp->refcount_inc (); }
  template<class T> static T *rp (const ::ref<T> &r) { return r.p; }
  template<class T> static T *rp (const ::ptr<T> &r) { return r.p; }
  template<class T, reftype v> static T *rp (refcounted<T, v> *pp)
    { return *pp; }
  static refcount *rc (refcount *c) { return c; } // Make gcc happy ???
  template<class T> static refcount *rc (const ::ref<T> &r) { return r.c; }
  template<class T> static refcount *rc (const ::ptr<T> &r) { return r.c; }
  template<class T, reftype v> static refcount *rc (refcounted<T, v> *pp)
    { return pp; }

  refcount *c;
  explicit refpriv (refcount *cc) : c (cc) {}
  refpriv () {}

public:
#if 0
  template<class T> bool operator== (const ::ref<T> &r) const
    { return c == r.c; }
  template<class T> bool operator== (const ::ptr<T> &r) const
    { return c == r.c; }
  template<class T> bool operator!= (const ::ref<T> &r) const
    { return c != r.c; }
  template<class T> bool operator!= (const ::ptr<T> &r) const
    { return c != r.c; }
#else
  bool operator== (const refpriv &r) const { return c == r.c; }
  bool operator!= (const refpriv &r) const { return c != r.c; }
#endif

  void *Xleak () const { rinc (c); return c; }
  static void Xplug (void *c) { rdec ((refcount *) c); }
};

template<class T> struct type2struct {
  typedef T type;
};
#define TYPE2STRUCT(t, T)			\
template<t> struct type2struct<T> {		\
  struct type {					\
    T v;					\
    operator T &() { return v; }		\
    operator const T &() const { return v; }	\
    type () {}					\
    type (const T &vv) : v (vv) {}		\
  };						\
}
TYPE2STRUCT(, bool);
TYPE2STRUCT(, char);
TYPE2STRUCT(, signed char);
TYPE2STRUCT(, unsigned char);
TYPE2STRUCT(, int);
TYPE2STRUCT(, unsigned int);
TYPE2STRUCT(, long);
TYPE2STRUCT(, unsigned long);
TYPE2STRUCT(class U, U *);

template<class T>
class refcounted<T, scalar>
  : virtual private refcount, private type2struct<T>::type
{
  friend class refpriv;

  virtual void XXX_gcc_repo_workaround () {} // XXX - egcs bug

  operator T *() { return &static_cast<T &> (*this); }
  /* When the reference count on an object goes to 0, the object is
   * deleted by default.  However, some classes may not wish to
   * deallocate their memory at the time the reference count goes to
   * 0.  (For example, a network stream class may wish to finish
   * writing buffered data to the network asynchronously, and delete
   * itself at a later point.)
   *
   * Classes can therefore specify a (non-virtual) "void finalize ()"
   * method to be called when the reference count goes to 0.  Any
   * class with a finalize method must also have refcount as a virtual
   * base class.
   *
   * So what is refcount_call_finalize all about?  Here is a more
   * obvious implementation:
   *
   *   class refcount {
   *     virtual void finalize () { delete this; }
   *     virtual ~refcount () {}
   *     ...
   *     void refcount_dec () { if (!--refcount_cnt) finalize (); }
   *   };
   *
   *   class myclass : public virtual refcount {
   *     void finalize () { ... }
   *   };
   *
   * But there are inconveniences.  If the user forgets to give
   * myclass a virtual refcount supertype, the code will still
   * compile--it will just behave incorrectly at run time.
   *
   * This code solves the problem by calling finalize from
   * refcounted<T> rather than refcount.  If the user forgets to give
   * myclass a virtual refount subtype, the call to finalize from
   * refount_call_finalize is ambiguous and flags an error.
   *
   * An added benefit of this scheme is that refcount is now a pure
   * virtual class (call_finalize is an abstract method).  This means
   * myclass also becomes a pure virtual class, and cannot be
   * allocated on its own (only as part of a refcounted<T>).  Of
   * course, if you really want to circumvent this restriction, you
   * can do so by giving myclass a virtual call_finalize() method.
   * The common case will probably be that a class with a finalize
   * method always expects to be refcounted.  This scheme makes it
   * hard to violate the requirement accidentally. */
  void refcount_call_finalize () {
    /* An error on the following line probably means you forgot to
     * give T a virtual base class of refcount.  Alternatively, T
     * already has a method called finalize unrelated to the reference
     * counting.  In that case you will have to rename finalize to use
     * a refcounted<T>. */
    finalize ();
  }

  ~refcounted () {}

public:
  VA_TEMPLATE (explicit refcounted, : type2struct<T>::type, {})
};

template<class T>
class refcounted<T, vsize>
  : virtual private refcount
{
  friend class refpriv;
  typedef refcounted<T, vsize> rc_t;

  virtual void XXX_gcc_repo_workaround () {} // XXX - egcs bug

  operator T *() { return tptr (this); }
  refcounted () { new ((void *) tptr (this)) T; }
  void refcount_call_finalize () {
    tptr (this)->~T ();
    delete this;
  }
  
  ~refcounted () {}

public:
  static rc_t *alloc (size_t n)
    { return new (opnew (n + (size_t) tptr (NULL))) rc_t; }
  static T *tptr (rc_t *rcp)
    { return (T *) ((char *) rcp + (sizeof (*rcp) + 7 & ~7)); }
};

#define REFOPS_DEFAULT(T)			\
protected:					\
  T *p;						\
  refops () {}					\
						\
public:						\
  T *get () const { return p; }			\
  operator T *() const { return p; }		\
  T *operator-> () const { return p; }		\
  T &operator* () const { return *p; }

template<class T>
class refops {
  REFOPS_DEFAULT (T)
};

template<>
class refops<void> {
protected:
  void *p;
  refops () {}

public:
  operator void *() const { return p; }
  void *get () const { return p; }
};

template<class T>
class ref : public refpriv, public refops<T> {
  friend class refpriv;

  friend ref<T> mkref<T> (T *);
  ref (T *pp, refcount *cc) : refpriv (cc) { p = pp; inc (); }

  void inc () const { rinc (c); }
  void dec () const { rdec (c); }

public:
  typedef T type;
  typedef ptr<T> ptr;

  template<class U, reftype v>
  ref (refcounted<U, v> *pp)
    : refpriv (rc (pp)) { p = refpriv::rp (pp); inc (); }
  /* At least with gcc, the copy constructor must be explicitly
   * defined (though it would appear to be redundant given the
   * template constructor bellow). */
  ref (const ref<T> &r) : refpriv (r.c) { p = r.p; inc (); }
  template<class U>
  ref (const ref<U> &r)
    : refpriv (rc (r)) { p = refpriv::rp (r); inc (); }
  template<class U>
  ref (const ::ptr<U> &r)
    : refpriv (rc (r)) { p = refpriv::rp (r); inc (); }

  ~ref () { dec (); }

  template<class U, reftype v> ref<T> &operator= (refcounted<U, v> *pp)
    { rinc (pp); dec (); p = refpriv::rp (pp); c = rc (pp); return *this; }

  /* The copy assignment operator must also explicitly be defined,
   * despite a redundant template. */
  ref<T> &operator= (const ref<T> &r)
    { r.inc (); dec (); p = r.p; c = r.c; return *this; }
  template<class U> ref<T> &operator= (const ref<U> &r)
    { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; }
  /* Self asignment not possible.  Use ref::inc to cause segfauls on NULL. */
  template<class U> ref<T> &operator= (const ::ptr<U> &r)
    { dec (); p = refpriv::rp (r); c = rc (r); inc (); return *this; }
};

/* To skip initialization of ptr's in BSS */
struct __bss_init {};

template<class T>
class ptr : public refpriv, public refops <T> {
  friend class refpriv;

  void inc () const { if (c) (rinc (c)); }
  void dec () const { if (c) (rdec (c)); }

  template<class U, reftype v>
  void set (refcounted<U, v> *pp, bool decme) {
    if (pp) {
      rinc (pp);
      if (decme)
	dec ();
      p = refpriv::rp (pp);
      c = rc (pp);
    }
    else {
      if (decme)
	dec ();
      p = NULL;
      c = NULL;
    }
  }

public:
  typedef T type;
  typedef ref<T> ref;

  explicit ptr (__bss_init) {}
  ptr () : refpriv (NULL) { p = NULL; }
  ptr (privtype *) : refpriv (NULL) { p = NULL; }
  template<class U, reftype v>
  ptr (refcounted<U, v> *pp) { set (pp, false); }
  ptr (const ptr<T> &r) : refpriv (r.c) { p = r.p; inc (); }
  template<class U>
  ptr (const ptr<U> &r)
    : refpriv (rc (r)) { p = refpriv::rp (r); inc (); }
  template<class U>
  ptr (const ::ref<U> &r)
    : refpriv (rc (r)) { p = refpriv::rp (r); inc (); }

  ~ptr () { dec (); }

  ptr<T> &operator= (privtype *)
    { dec (); p = NULL; c = NULL; return *this; }
  template<class U, reftype v> ptr<T> &operator= (refcounted<U, v> *pp)
    { set (pp, true); return *this; }

  ptr<T> &operator= (const ptr<T> &r)
    { r.inc (); dec (); p = r.p; c = r.c; return *this; }
  template<class U> ptr<T> &operator= (const ptr<U> &r)
    { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; }
  template<class U> ptr<T> &operator= (const ::ref<U> &r)
    { rinc (r); dec (); p = refpriv::rp (r); c = rc (r); return *this; }
};

template<class T>
struct bssptr : ptr<T> {
  // Don't initialize (assume we were 0 initialized in the BSS)
  bssptr () : ptr<T> (__bss_init ()) {}
  // Override the effects of destruction
  ~bssptr () { assert (globaldestruction); if (*this != NULL) Xleak (); }
  ptr<T> &operator= (refpriv::privtype *p) { return ptr<T>::operator= (p); }
  template<class U> ptr<T> &operator= (const ptr<U> &r)
    { return ptr<T>::operator= (r); }
  template<class U> ptr<T> &operator= (const ::ref<U> &r)
    { return ptr<T>::operator= (r); }
};

template<class T> inline ref<T>
mkref (T *p)
{
  return ref<T> (p, p);
}

#endif /* !_REFCNT_H_INCLUDED_ */