blob: 37fcc51906c0e81fb96c1e01dd58bd56fc8b7ace [file] [log] [blame]
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001/*
Tim Peters88396172002-06-30 17:56:40 +00002
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00003 Reference Cycle Garbage Collection
4 ==================================
5
Neil Schemenauerb2c2c9e2000-10-04 16:34:09 +00006 Neil Schemenauer <nas@arctrix.com>
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00007
8 Based on a post on the python-dev list. Ideas from Guido van Rossum,
9 Eric Tiedemann, and various others.
10
Neil Schemenauer43411b52001-08-30 00:05:51 +000011 http://www.arctrix.com/nas/python/gc/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000012 http://www.python.org/pipermail/python-dev/2000-March/003869.html
13 http://www.python.org/pipermail/python-dev/2000-March/004010.html
14 http://www.python.org/pipermail/python-dev/2000-March/004022.html
15
16 For a highlevel view of the collection process, read the collect
17 function.
18
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000019*/
20
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000021#include "Python.h"
22
Neil Schemenauer43411b52001-08-30 00:05:51 +000023/* Get an object's GC head */
24#define AS_GC(o) ((PyGC_Head *)(o)-1)
25
26/* Get the object given the GC head */
27#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
28
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000029/*** Global GC state ***/
30
Neil Schemenauer2880ae52002-05-04 05:35:20 +000031struct gc_generation {
32 PyGC_Head head;
33 int threshold; /* collection threshold */
34 int count; /* count of allocations or collections of younger
35 generations */
36};
37
38#define NUM_GENERATIONS 3
39#define GEN_HEAD(n) (&generations[n].head)
40
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000041/* linked lists of container objects */
Neil Schemenauer2880ae52002-05-04 05:35:20 +000042static struct gc_generation generations[NUM_GENERATIONS] = {
43 /* PyGC_Head, threshold, count */
44 {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
45 {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
46 {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
47};
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000048
Neil Schemenauer2880ae52002-05-04 05:35:20 +000049PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);
50
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +000051static int enabled = 1; /* automatic collection enabled? */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000052
Neil Schemenauer43411b52001-08-30 00:05:51 +000053/* true if we are currently running the collector */
Tim Petersbf384c22003-04-06 00:11:39 +000054static int collecting = 0;
Neil Schemenauer43411b52001-08-30 00:05:51 +000055
Tim Peters6fc13d92002-07-02 18:12:35 +000056/* list of uncollectable objects */
Tim Petersbf384c22003-04-06 00:11:39 +000057static PyObject *garbage = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000058
59/* Python string to use if unhandled exception occurs */
Tim Petersbf384c22003-04-06 00:11:39 +000060static PyObject *gc_str = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000061
Tim Peters93ad66d2003-04-05 17:15:44 +000062/* Python string used to look for __del__ attribute. */
63static PyObject *delstr = NULL;
Jeremy Hyltonce136e92003-04-04 19:59:06 +000064
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000065/* set for debugging information */
66#define DEBUG_STATS (1<<0) /* print collection statistics */
67#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
68#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
Neil Schemenauer544de1e2000-09-22 15:22:38 +000069#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000070#define DEBUG_LEAK DEBUG_COLLECTABLE | \
71 DEBUG_UNCOLLECTABLE | \
Neil Schemenauer544de1e2000-09-22 15:22:38 +000072 DEBUG_SAVEALL
Jeremy Hyltonb709df32000-09-01 02:47:25 +000073static int debug;
Thomas Wouters477c8d52006-05-27 19:21:47 +000074static PyObject *tmod = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000075
Tim Peters6fc13d92002-07-02 18:12:35 +000076/*--------------------------------------------------------------------------
77gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +000078
Tim Peters6fc13d92002-07-02 18:12:35 +000079Between collections, every gc'ed object has one of two gc_refs values:
80
81GC_UNTRACKED
82 The initial state; objects returned by PyObject_GC_Malloc are in this
83 state. The object doesn't live in any generation list, and its
84 tp_traverse slot must not be called.
85
86GC_REACHABLE
87 The object lives in some generation list, and its tp_traverse is safe to
88 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
89 is called.
90
91During a collection, gc_refs can temporarily take on other states:
92
93>= 0
94 At the start of a collection, update_refs() copies the true refcount
95 to gc_refs, for each object in the generation being collected.
96 subtract_refs() then adjusts gc_refs so that it equals the number of
97 times an object is referenced directly from outside the generation
98 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +000099 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000100
101GC_TENTATIVELY_UNREACHABLE
102 move_unreachable() then moves objects not reachable (whether directly or
103 indirectly) from outside the generation into an "unreachable" set.
104 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
105 again. Objects that are found to be unreachable have gc_refs set to
106 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
107 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
108 transition back to GC_REACHABLE.
109
110 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
111 for collection. If it's decided not to collect such an object (e.g.,
112 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
113----------------------------------------------------------------------------
114*/
Tim Petersea405632002-07-02 00:52:30 +0000115#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
116#define GC_REACHABLE _PyGC_REFS_REACHABLE
117#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000118
Tim Peters6fc13d92002-07-02 18:12:35 +0000119#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)
Tim Peters19b74c72002-07-01 03:52:19 +0000120#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)
121#define IS_TENTATIVELY_UNREACHABLE(o) ( \
122 (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000123
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000124/*** list functions ***/
125
126static void
127gc_list_init(PyGC_Head *list)
128{
Tim Peters9e4ca102001-10-11 18:31:31 +0000129 list->gc.gc_prev = list;
130 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000131}
132
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000133static int
134gc_list_is_empty(PyGC_Head *list)
135{
136 return (list->gc.gc_next == list);
137}
138
Tim Peterse2d59182004-11-01 01:39:08 +0000139#if 0
140/* This became unused after gc_list_move() was introduced. */
141/* Append `node` to `list`. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000142static void
143gc_list_append(PyGC_Head *node, PyGC_Head *list)
144{
Tim Peters9e4ca102001-10-11 18:31:31 +0000145 node->gc.gc_next = list;
146 node->gc.gc_prev = list->gc.gc_prev;
147 node->gc.gc_prev->gc.gc_next = node;
148 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000149}
Tim Peterse2d59182004-11-01 01:39:08 +0000150#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000151
Tim Peterse2d59182004-11-01 01:39:08 +0000152/* Remove `node` from the gc list it's currently in. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000153static void
154gc_list_remove(PyGC_Head *node)
155{
Tim Peters9e4ca102001-10-11 18:31:31 +0000156 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
157 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
158 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000159}
160
Tim Peterse2d59182004-11-01 01:39:08 +0000161/* Move `node` from the gc list it's currently in (which is not explicitly
162 * named here) to the end of `list`. This is semantically the same as
163 * gc_list_remove(node) followed by gc_list_append(node, list).
164 */
165static void
166gc_list_move(PyGC_Head *node, PyGC_Head *list)
167{
Tim Petersbc1d1b82004-11-01 16:39:57 +0000168 PyGC_Head *new_prev;
Tim Peterse2d59182004-11-01 01:39:08 +0000169 PyGC_Head *current_prev = node->gc.gc_prev;
170 PyGC_Head *current_next = node->gc.gc_next;
Tim Petersbc1d1b82004-11-01 16:39:57 +0000171 /* Unlink from current list. */
Tim Peterse2d59182004-11-01 01:39:08 +0000172 current_prev->gc.gc_next = current_next;
173 current_next->gc.gc_prev = current_prev;
Tim Petersbc1d1b82004-11-01 16:39:57 +0000174 /* Relink at end of new list. */
175 new_prev = node->gc.gc_prev = list->gc.gc_prev;
Tim Peterse2d59182004-11-01 01:39:08 +0000176 new_prev->gc.gc_next = list->gc.gc_prev = node;
Tim Petersbc1d1b82004-11-01 16:39:57 +0000177 node->gc.gc_next = list;
Tim Peterse2d59182004-11-01 01:39:08 +0000178}
179
180/* append list `from` onto list `to`; `from` becomes an empty list */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000181static void
182gc_list_merge(PyGC_Head *from, PyGC_Head *to)
183{
184 PyGC_Head *tail;
Tim Peterse2d59182004-11-01 01:39:08 +0000185 assert(from != to);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000186 if (!gc_list_is_empty(from)) {
Tim Peters9e4ca102001-10-11 18:31:31 +0000187 tail = to->gc.gc_prev;
188 tail->gc.gc_next = from->gc.gc_next;
189 tail->gc.gc_next->gc.gc_prev = tail;
190 to->gc.gc_prev = from->gc.gc_prev;
191 to->gc.gc_prev->gc.gc_next = to;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000192 }
193 gc_list_init(from);
194}
195
Neal Norwitz7b216c52006-03-04 20:01:53 +0000196static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000197gc_list_size(PyGC_Head *list)
198{
199 PyGC_Head *gc;
Neal Norwitz7b216c52006-03-04 20:01:53 +0000200 Py_ssize_t n = 0;
Tim Peters9e4ca102001-10-11 18:31:31 +0000201 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000202 n++;
203 }
204 return n;
205}
206
Tim Peters259272b2003-04-06 19:41:39 +0000207/* Append objects in a GC list to a Python list.
208 * Return 0 if all OK, < 0 if error (out of memory for list).
209 */
210static int
211append_objects(PyObject *py_list, PyGC_Head *gc_list)
212{
213 PyGC_Head *gc;
214 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
215 PyObject *op = FROM_GC(gc);
216 if (op != py_list) {
217 if (PyList_Append(py_list, op)) {
218 return -1; /* exception */
219 }
220 }
221 }
222 return 0;
223}
224
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000225/*** end of list stuff ***/
226
227
Tim Peters19b74c72002-07-01 03:52:19 +0000228/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
229 * in containers, and is GC_REACHABLE for all tracked gc objects not in
230 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000231 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000232static void
233update_refs(PyGC_Head *containers)
234{
Tim Peters9e4ca102001-10-11 18:31:31 +0000235 PyGC_Head *gc = containers->gc.gc_next;
Tim Petersea405632002-07-02 00:52:30 +0000236 for (; gc != containers; gc = gc->gc.gc_next) {
237 assert(gc->gc.gc_refs == GC_REACHABLE);
Christian Heimes90aa7642007-12-19 02:45:37 +0000238 gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
Tim Peters780c4972003-11-14 00:01:17 +0000239 /* Python's cyclic gc should never see an incoming refcount
240 * of 0: if something decref'ed to 0, it should have been
241 * deallocated immediately at that time.
242 * Possible cause (if the assert triggers): a tp_dealloc
243 * routine left a gc-aware object tracked during its teardown
244 * phase, and did something-- or allowed something to happen --
245 * that called back into Python. gc can trigger then, and may
246 * see the still-tracked dying object. Before this assert
247 * was added, such mistakes went on to allow gc to try to
248 * delete the object again. In a debug build, that caused
249 * a mysterious segfault, when _Py_ForgetReference tried
250 * to remove the object from the doubly-linked list of all
251 * objects a second time. In a release build, an actual
252 * double deallocation occurred, which leads to corruption
253 * of the allocator's internal bookkeeping pointers. That's
254 * so serious that maybe this should be a release-build
255 * check instead of an assert?
256 */
257 assert(gc->gc.gc_refs != 0);
Tim Petersea405632002-07-02 00:52:30 +0000258 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000259}
260
Tim Peters19b74c72002-07-01 03:52:19 +0000261/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000262static int
263visit_decref(PyObject *op, void *data)
264{
Tim Peters93cd83e2002-06-30 21:31:03 +0000265 assert(op != NULL);
Tim Peters19b74c72002-07-01 03:52:19 +0000266 if (PyObject_IS_GC(op)) {
267 PyGC_Head *gc = AS_GC(op);
268 /* We're only interested in gc_refs for objects in the
269 * generation being collected, which can be recognized
270 * because only they have positive gc_refs.
271 */
Tim Petersaab713b2002-07-02 22:15:28 +0000272 assert(gc->gc.gc_refs != 0); /* else refcount was too small */
Tim Peters19b74c72002-07-01 03:52:19 +0000273 if (gc->gc.gc_refs > 0)
274 gc->gc.gc_refs--;
275 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000276 return 0;
277}
278
Tim Peters19b74c72002-07-01 03:52:19 +0000279/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
280 * for all objects in containers, and is GC_REACHABLE for all tracked gc
281 * objects not in containers. The ones with gc_refs > 0 are directly
282 * reachable from outside containers, and so can't be collected.
283 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000284static void
285subtract_refs(PyGC_Head *containers)
286{
287 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000288 PyGC_Head *gc = containers->gc.gc_next;
289 for (; gc != containers; gc=gc->gc.gc_next) {
Christian Heimes90aa7642007-12-19 02:45:37 +0000290 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000291 (void) traverse(FROM_GC(gc),
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000292 (visitproc)visit_decref,
293 NULL);
294 }
295}
296
Tim Peters19b74c72002-07-01 03:52:19 +0000297/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000298static int
Tim Peters19b74c72002-07-01 03:52:19 +0000299visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000300{
Tim Petersea405632002-07-02 00:52:30 +0000301 if (PyObject_IS_GC(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000302 PyGC_Head *gc = AS_GC(op);
Martin v. Löwis6db0e002006-03-01 16:56:25 +0000303 const Py_ssize_t gc_refs = gc->gc.gc_refs;
Tim Peters19b74c72002-07-01 03:52:19 +0000304
305 if (gc_refs == 0) {
306 /* This is in move_unreachable's 'young' list, but
307 * the traversal hasn't yet gotten to it. All
308 * we need to do is tell move_unreachable that it's
309 * reachable.
310 */
311 gc->gc.gc_refs = 1;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000312 }
Tim Peters19b74c72002-07-01 03:52:19 +0000313 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
314 /* This had gc_refs = 0 when move_unreachable got
315 * to it, but turns out it's reachable after all.
316 * Move it back to move_unreachable's 'young' list,
317 * and move_unreachable will eventually get to it
318 * again.
319 */
Tim Peterse2d59182004-11-01 01:39:08 +0000320 gc_list_move(gc, reachable);
Tim Peters19b74c72002-07-01 03:52:19 +0000321 gc->gc.gc_refs = 1;
322 }
323 /* Else there's nothing to do.
324 * If gc_refs > 0, it must be in move_unreachable's 'young'
325 * list, and move_unreachable will eventually get to it.
326 * If gc_refs == GC_REACHABLE, it's either in some other
327 * generation so we don't care about it, or move_unreachable
Tim Peters6fc13d92002-07-02 18:12:35 +0000328 * already dealt with it.
Tim Petersea405632002-07-02 00:52:30 +0000329 * If gc_refs == GC_UNTRACKED, it must be ignored.
Tim Peters19b74c72002-07-01 03:52:19 +0000330 */
Tim Petersea405632002-07-02 00:52:30 +0000331 else {
332 assert(gc_refs > 0
333 || gc_refs == GC_REACHABLE
334 || gc_refs == GC_UNTRACKED);
335 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000336 }
337 return 0;
338}
339
Tim Peters19b74c72002-07-01 03:52:19 +0000340/* Move the unreachable objects from young to unreachable. After this,
341 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
342 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
343 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
344 * All objects in young after this are directly or indirectly reachable
345 * from outside the original young; and all objects in unreachable are
346 * not.
Tim Peters88396172002-06-30 17:56:40 +0000347 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000348static void
Tim Peters19b74c72002-07-01 03:52:19 +0000349move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000350{
Tim Peters19b74c72002-07-01 03:52:19 +0000351 PyGC_Head *gc = young->gc.gc_next;
352
353 /* Invariants: all objects "to the left" of us in young have gc_refs
354 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
355 * from outside the young list as it was at entry. All other objects
356 * from the original young "to the left" of us are in unreachable now,
357 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
358 * left of us in 'young' now have been scanned, and no objects here
359 * or to the right have been scanned yet.
360 */
361
362 while (gc != young) {
363 PyGC_Head *next;
364
Tim Peters6fc13d92002-07-02 18:12:35 +0000365 if (gc->gc.gc_refs) {
366 /* gc is definitely reachable from outside the
367 * original 'young'. Mark it as such, and traverse
368 * its pointers to find any other objects that may
369 * be directly reachable from it. Note that the
370 * call to tp_traverse may append objects to young,
371 * so we have to wait until it returns to determine
372 * the next object to visit.
373 */
374 PyObject *op = FROM_GC(gc);
Christian Heimes90aa7642007-12-19 02:45:37 +0000375 traverseproc traverse = Py_TYPE(op)->tp_traverse;
Tim Peters6fc13d92002-07-02 18:12:35 +0000376 assert(gc->gc.gc_refs > 0);
377 gc->gc.gc_refs = GC_REACHABLE;
378 (void) traverse(op,
379 (visitproc)visit_reachable,
380 (void *)young);
381 next = gc->gc.gc_next;
382 }
383 else {
Tim Peters19b74c72002-07-01 03:52:19 +0000384 /* This *may* be unreachable. To make progress,
385 * assume it is. gc isn't directly reachable from
386 * any object we've already traversed, but may be
387 * reachable from an object we haven't gotten to yet.
388 * visit_reachable will eventually move gc back into
389 * young if that's so, and we'll see it again.
390 */
391 next = gc->gc.gc_next;
Tim Peterse2d59182004-11-01 01:39:08 +0000392 gc_list_move(gc, unreachable);
Tim Peters19b74c72002-07-01 03:52:19 +0000393 gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
394 }
Tim Peters19b74c72002-07-01 03:52:19 +0000395 gc = next;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000396 }
397}
398
Amaury Forgeot d'Arcad8dcd52007-12-10 23:58:35 +0000399/* Return true if object has a finalization method. */
Neil Schemenauera765c122001-11-01 17:35:23 +0000400static int
401has_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000402{
Guido van Rossum50e9fb92006-08-17 05:42:55 +0000403 if (PyGen_CheckExact(op))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404 return PyGen_NeedsFinalizing((PyGenObject *)op);
405 else
Thomas Wouters3dfc3c12006-08-21 22:15:41 +0000406 return op->ob_type->tp_del != NULL;
Neil Schemenauera765c122001-11-01 17:35:23 +0000407}
408
Tim Petersead8b7a2004-10-30 23:09:22 +0000409/* Move the objects in unreachable with __del__ methods into `finalizers`.
410 * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the
411 * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000412 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000413static void
Tim Petersead8b7a2004-10-30 23:09:22 +0000414move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000415{
Tim Petersead8b7a2004-10-30 23:09:22 +0000416 PyGC_Head *gc;
417 PyGC_Head *next;
Tim Petersf6b80452003-04-07 19:21:15 +0000418
Tim Petersead8b7a2004-10-30 23:09:22 +0000419 /* March over unreachable. Move objects with finalizers into
420 * `finalizers`.
421 */
422 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000423 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000424
Tim Petersf6ae7a42003-04-05 18:40:50 +0000425 assert(IS_TENTATIVELY_UNREACHABLE(op));
Tim Petersead8b7a2004-10-30 23:09:22 +0000426 next = gc->gc.gc_next;
Tim Petersf6ae7a42003-04-05 18:40:50 +0000427
Tim Petersf6b80452003-04-07 19:21:15 +0000428 if (has_finalizer(op)) {
Tim Peterse2d59182004-11-01 01:39:08 +0000429 gc_list_move(gc, finalizers);
Tim Petersf6b80452003-04-07 19:21:15 +0000430 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000431 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000432 }
433}
434
Tim Peters19b74c72002-07-01 03:52:19 +0000435/* A traversal callback for move_finalizer_reachable. */
436static int
437visit_move(PyObject *op, PyGC_Head *tolist)
438{
439 if (PyObject_IS_GC(op)) {
Tim Petersea405632002-07-02 00:52:30 +0000440 if (IS_TENTATIVELY_UNREACHABLE(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000441 PyGC_Head *gc = AS_GC(op);
Tim Peterse2d59182004-11-01 01:39:08 +0000442 gc_list_move(gc, tolist);
Tim Peters19b74c72002-07-01 03:52:19 +0000443 gc->gc.gc_refs = GC_REACHABLE;
444 }
445 }
446 return 0;
447}
448
449/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersf6b80452003-04-07 19:21:15 +0000450 * into finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000451 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000452static void
Tim Petersf6b80452003-04-07 19:21:15 +0000453move_finalizer_reachable(PyGC_Head *finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000454{
455 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000456 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000457 for (; gc != finalizers; gc = gc->gc.gc_next) {
458 /* Note that the finalizers list may grow during this. */
Christian Heimes90aa7642007-12-19 02:45:37 +0000459 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
Tim Peters88396172002-06-30 17:56:40 +0000460 (void) traverse(FROM_GC(gc),
Tim Petersbf384c22003-04-06 00:11:39 +0000461 (visitproc)visit_move,
Tim Petersf6b80452003-04-07 19:21:15 +0000462 (void *)finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000463 }
464}
465
Tim Petersead8b7a2004-10-30 23:09:22 +0000466/* Clear all weakrefs to unreachable objects, and if such a weakref has a
467 * callback, invoke it if necessary. Note that it's possible for such
468 * weakrefs to be outside the unreachable set -- indeed, those are precisely
469 * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
470 * overview & some details. Some weakrefs with callbacks may be reclaimed
471 * directly by this routine; the number reclaimed is the return value. Other
472 * weakrefs with callbacks may be moved into the `old` generation. Objects
473 * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
474 * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
475 * no object in `unreachable` is weakly referenced anymore.
Tim Peters403a2032003-11-20 21:21:46 +0000476 */
477static int
Tim Petersead8b7a2004-10-30 23:09:22 +0000478handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
Tim Peters403a2032003-11-20 21:21:46 +0000479{
Tim Petersead8b7a2004-10-30 23:09:22 +0000480 PyGC_Head *gc;
481 PyObject *op; /* generally FROM_GC(gc) */
482 PyWeakReference *wr; /* generally a cast of op */
Tim Petersead8b7a2004-10-30 23:09:22 +0000483 PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
Tim Petersead8b7a2004-10-30 23:09:22 +0000484 PyGC_Head *next;
Tim Peters403a2032003-11-20 21:21:46 +0000485 int num_freed = 0;
486
Tim Petersead8b7a2004-10-30 23:09:22 +0000487 gc_list_init(&wrcb_to_call);
Tim Peters403a2032003-11-20 21:21:46 +0000488
Tim Petersead8b7a2004-10-30 23:09:22 +0000489 /* Clear all weakrefs to the objects in unreachable. If such a weakref
490 * also has a callback, move it into `wrcb_to_call` if the callback
Tim Peterscc2a8662004-10-31 22:12:43 +0000491 * needs to be invoked. Note that we cannot invoke any callbacks until
492 * all weakrefs to unreachable objects are cleared, lest the callback
493 * resurrect an unreachable object via a still-active weakref. We
494 * make another pass over wrcb_to_call, invoking callbacks, after this
495 * pass completes.
Tim Petersead8b7a2004-10-30 23:09:22 +0000496 */
497 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
498 PyWeakReference **wrlist;
499
500 op = FROM_GC(gc);
501 assert(IS_TENTATIVELY_UNREACHABLE(op));
502 next = gc->gc.gc_next;
503
Christian Heimes90aa7642007-12-19 02:45:37 +0000504 if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
Tim Petersead8b7a2004-10-30 23:09:22 +0000505 continue;
506
507 /* It supports weakrefs. Does it have any? */
508 wrlist = (PyWeakReference **)
509 PyObject_GET_WEAKREFS_LISTPTR(op);
510
511 /* `op` may have some weakrefs. March over the list, clear
512 * all the weakrefs, and move the weakrefs with callbacks
Tim Peterscc2a8662004-10-31 22:12:43 +0000513 * that must be called into wrcb_to_call.
Tim Petersead8b7a2004-10-30 23:09:22 +0000514 */
515 for (wr = *wrlist; wr != NULL; wr = *wrlist) {
516 PyGC_Head *wrasgc; /* AS_GC(wr) */
517
518 /* _PyWeakref_ClearRef clears the weakref but leaves
519 * the callback pointer intact. Obscure: it also
520 * changes *wrlist.
521 */
522 assert(wr->wr_object == op);
523 _PyWeakref_ClearRef(wr);
524 assert(wr->wr_object == Py_None);
525 if (wr->wr_callback == NULL)
526 continue; /* no callback */
527
528 /* Headache time. `op` is going away, and is weakly referenced by
529 * `wr`, which has a callback. Should the callback be invoked? If wr
530 * is also trash, no:
531 *
532 * 1. There's no need to call it. The object and the weakref are
533 * both going away, so it's legitimate to pretend the weakref is
534 * going away first. The user has to ensure a weakref outlives its
535 * referent if they want a guarantee that the wr callback will get
536 * invoked.
537 *
538 * 2. It may be catastrophic to call it. If the callback is also in
539 * cyclic trash (CT), then although the CT is unreachable from
540 * outside the current generation, CT may be reachable from the
541 * callback. Then the callback could resurrect insane objects.
542 *
543 * Since the callback is never needed and may be unsafe in this case,
Tim Peterscc2a8662004-10-31 22:12:43 +0000544 * wr is simply left in the unreachable set. Note that because we
545 * already called _PyWeakref_ClearRef(wr), its callback will never
546 * trigger.
Tim Petersead8b7a2004-10-30 23:09:22 +0000547 *
548 * OTOH, if wr isn't part of CT, we should invoke the callback: the
549 * weakref outlived the trash. Note that since wr isn't CT in this
550 * case, its callback can't be CT either -- wr acted as an external
551 * root to this generation, and therefore its callback did too. So
552 * nothing in CT is reachable from the callback either, so it's hard
553 * to imagine how calling it later could create a problem for us. wr
554 * is moved to wrcb_to_call in this case.
Tim Petersead8b7a2004-10-30 23:09:22 +0000555 */
Tim Peterscc2a8662004-10-31 22:12:43 +0000556 if (IS_TENTATIVELY_UNREACHABLE(wr))
557 continue;
558 assert(IS_REACHABLE(wr));
559
Tim Petersead8b7a2004-10-30 23:09:22 +0000560 /* Create a new reference so that wr can't go away
561 * before we can process it again.
562 */
563 Py_INCREF(wr);
564
Tim Peterscc2a8662004-10-31 22:12:43 +0000565 /* Move wr to wrcb_to_call, for the next pass. */
Tim Petersead8b7a2004-10-30 23:09:22 +0000566 wrasgc = AS_GC(wr);
Tim Peterscc2a8662004-10-31 22:12:43 +0000567 assert(wrasgc != next); /* wrasgc is reachable, but
568 next isn't, so they can't
569 be the same */
Tim Peterse2d59182004-11-01 01:39:08 +0000570 gc_list_move(wrasgc, &wrcb_to_call);
Tim Petersead8b7a2004-10-30 23:09:22 +0000571 }
572 }
573
Tim Peterscc2a8662004-10-31 22:12:43 +0000574 /* Invoke the callbacks we decided to honor. It's safe to invoke them
575 * because they can't reference unreachable objects.
Tim Petersead8b7a2004-10-30 23:09:22 +0000576 */
577 while (! gc_list_is_empty(&wrcb_to_call)) {
578 PyObject *temp;
579 PyObject *callback;
580
581 gc = wrcb_to_call.gc.gc_next;
582 op = FROM_GC(gc);
583 assert(IS_REACHABLE(op));
584 assert(PyWeakref_Check(op));
585 wr = (PyWeakReference *)op;
586 callback = wr->wr_callback;
587 assert(callback != NULL);
588
589 /* copy-paste of weakrefobject.c's handle_callback() */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000590 temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
Tim Petersead8b7a2004-10-30 23:09:22 +0000591 if (temp == NULL)
592 PyErr_WriteUnraisable(callback);
593 else
594 Py_DECREF(temp);
595
596 /* Give up the reference we created in the first pass. When
597 * op's refcount hits 0 (which it may or may not do right now),
Tim Peterscc2a8662004-10-31 22:12:43 +0000598 * op's tp_dealloc will decref op->wr_callback too. Note
599 * that the refcount probably will hit 0 now, and because this
600 * weakref was reachable to begin with, gc didn't already
601 * add it to its count of freed objects. Example: a reachable
602 * weak value dict maps some key to this reachable weakref.
603 * The callback removes this key->weakref mapping from the
604 * dict, leaving no other references to the weakref (excepting
605 * ours).
Tim Petersead8b7a2004-10-30 23:09:22 +0000606 */
607 Py_DECREF(op);
608 if (wrcb_to_call.gc.gc_next == gc) {
609 /* object is still alive -- move it */
Tim Peterse2d59182004-11-01 01:39:08 +0000610 gc_list_move(gc, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000611 }
612 else
613 ++num_freed;
614 }
615
Tim Peters403a2032003-11-20 21:21:46 +0000616 return num_freed;
617}
618
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000619static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000620debug_cycle(char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000621{
Amaury Forgeot d'Arcad8dcd52007-12-10 23:58:35 +0000622 PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
Christian Heimes90aa7642007-12-19 02:45:37 +0000623 msg, Py_TYPE(op)->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000624}
625
Tim Petersbf384c22003-04-06 00:11:39 +0000626/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
627 * only from such cycles).
Tim Petersf6b80452003-04-07 19:21:15 +0000628 * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
629 * garbage list (a Python list), else only the objects in finalizers with
630 * __del__ methods are appended to garbage. All objects in finalizers are
631 * merged into the old list regardless.
Tim Peters259272b2003-04-06 19:41:39 +0000632 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
633 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000634 */
Tim Peters259272b2003-04-06 19:41:39 +0000635static int
Tim Petersf6b80452003-04-07 19:21:15 +0000636handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000637{
Tim Petersf6b80452003-04-07 19:21:15 +0000638 PyGC_Head *gc = finalizers->gc.gc_next;
639
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000640 if (garbage == NULL) {
641 garbage = PyList_New(0);
Tim Petersbf384c22003-04-06 00:11:39 +0000642 if (garbage == NULL)
643 Py_FatalError("gc couldn't create gc.garbage list");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000644 }
Tim Petersf6b80452003-04-07 19:21:15 +0000645 for (; gc != finalizers; gc = gc->gc.gc_next) {
646 PyObject *op = FROM_GC(gc);
647
648 if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
649 if (PyList_Append(garbage, op) < 0)
650 return -1;
651 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000652 }
Tim Petersf6b80452003-04-07 19:21:15 +0000653
Tim Peters259272b2003-04-06 19:41:39 +0000654 gc_list_merge(finalizers, old);
655 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000656}
657
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000658/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000659 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000660 * objects may be freed. It is possible I screwed something up here.
661 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000662static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000663delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000664{
665 inquiry clear;
666
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000667 while (!gc_list_is_empty(collectable)) {
668 PyGC_Head *gc = collectable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000669 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000670
Tim Peters19b74c72002-07-01 03:52:19 +0000671 assert(IS_TENTATIVELY_UNREACHABLE(op));
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000672 if (debug & DEBUG_SAVEALL) {
673 PyList_Append(garbage, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000674 }
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000675 else {
Christian Heimes90aa7642007-12-19 02:45:37 +0000676 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000677 Py_INCREF(op);
Jeremy Hylton8a135182002-06-06 23:23:55 +0000678 clear(op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000679 Py_DECREF(op);
680 }
681 }
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000682 if (collectable->gc.gc_next == gc) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000683 /* object is still alive, move it, it may die later */
Tim Peterse2d59182004-11-01 01:39:08 +0000684 gc_list_move(gc, old);
Tim Peters19b74c72002-07-01 03:52:19 +0000685 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000686 }
687 }
688}
689
690/* This is the main function. Read this to understand how the
691 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000692static Py_ssize_t
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000693collect(int generation)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000694{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000695 int i;
Neal Norwitz7b216c52006-03-04 20:01:53 +0000696 Py_ssize_t m = 0; /* # objects collected */
697 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000698 PyGC_Head *young; /* the generation we are examining */
699 PyGC_Head *old; /* next older generation */
Tim Peters403a2032003-11-20 21:21:46 +0000700 PyGC_Head unreachable; /* non-problematic unreachable trash */
701 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000702 PyGC_Head *gc;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703 double t1 = 0.0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000704
Tim Peters93ad66d2003-04-05 17:15:44 +0000705 if (delstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000706 delstr = PyUnicode_InternFromString("__del__");
Tim Peters93ad66d2003-04-05 17:15:44 +0000707 if (delstr == NULL)
708 Py_FatalError("gc couldn't allocate \"__del__\"");
709 }
710
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000711 if (debug & DEBUG_STATS) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000712 if (tmod != NULL) {
713 PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
714 if (f == NULL) {
715 PyErr_Clear();
716 }
717 else {
718 t1 = PyFloat_AsDouble(f);
719 Py_DECREF(f);
720 }
721 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000722 PySys_WriteStderr("gc: collecting generation %d...\n",
723 generation);
724 PySys_WriteStderr("gc: objects in each generation:");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000725 for (i = 0; i < NUM_GENERATIONS; i++)
726 PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
727 gc_list_size(GEN_HEAD(i)));
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000728 PySys_WriteStderr("\n");
729 }
730
731 /* update collection and allocation counters */
732 if (generation+1 < NUM_GENERATIONS)
733 generations[generation+1].count += 1;
734 for (i = 0; i <= generation; i++)
Neil Schemenauerc9051642002-06-28 19:16:04 +0000735 generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000736
737 /* merge younger generations with one we are currently collecting */
738 for (i = 0; i < generation; i++) {
739 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
740 }
741
742 /* handy references */
743 young = GEN_HEAD(generation);
Tim Peters19b74c72002-07-01 03:52:19 +0000744 if (generation < NUM_GENERATIONS-1)
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000745 old = GEN_HEAD(generation+1);
Tim Peters19b74c72002-07-01 03:52:19 +0000746 else
747 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000748
749 /* Using ob_refcnt and gc_refs, calculate which objects in the
Tim Petersead8b7a2004-10-30 23:09:22 +0000750 * container set are reachable from outside the set (i.e., have a
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000751 * refcount greater than 0 when all the references within the
Tim Petersead8b7a2004-10-30 23:09:22 +0000752 * set are taken into account).
Tim Peters19b74c72002-07-01 03:52:19 +0000753 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000754 update_refs(young);
755 subtract_refs(young);
756
Tim Peters19b74c72002-07-01 03:52:19 +0000757 /* Leave everything reachable from outside young in young, and move
758 * everything else (in young) to unreachable.
759 * NOTE: This used to move the reachable objects into a reachable
760 * set instead. But most things usually turn out to be reachable,
761 * so it's more efficient to move the unreachable things.
762 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000763 gc_list_init(&unreachable);
Tim Peters19b74c72002-07-01 03:52:19 +0000764 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000765
Tim Peters19b74c72002-07-01 03:52:19 +0000766 /* Move reachable objects to next generation. */
767 if (young != old)
768 gc_list_merge(young, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000769
Tim Peters19b74c72002-07-01 03:52:19 +0000770 /* All objects in unreachable are trash, but objects reachable from
771 * finalizers can't safely be deleted. Python programmers should take
772 * care not to create such things. For Python, finalizers means
Tim Peters403a2032003-11-20 21:21:46 +0000773 * instance objects with __del__ methods. Weakrefs with callbacks
Tim Petersead8b7a2004-10-30 23:09:22 +0000774 * can also call arbitrary Python code but they will be dealt with by
775 * handle_weakrefs().
Tim Petersf6b80452003-04-07 19:21:15 +0000776 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000777 gc_list_init(&finalizers);
Tim Petersead8b7a2004-10-30 23:09:22 +0000778 move_finalizers(&unreachable, &finalizers);
Tim Petersbf384c22003-04-06 00:11:39 +0000779 /* finalizers contains the unreachable objects with a finalizer;
Tim Peters403a2032003-11-20 21:21:46 +0000780 * unreachable objects reachable *from* those are also uncollectable,
781 * and we move those into the finalizers list too.
Tim Petersbf384c22003-04-06 00:11:39 +0000782 */
Tim Petersf6b80452003-04-07 19:21:15 +0000783 move_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000784
785 /* Collect statistics on collectable objects found and print
Tim Peters403a2032003-11-20 21:21:46 +0000786 * debugging information.
787 */
Tim Petersf6b80452003-04-07 19:21:15 +0000788 for (gc = unreachable.gc.gc_next; gc != &unreachable;
Tim Peters9e4ca102001-10-11 18:31:31 +0000789 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000790 m++;
Jeremy Hylton06257772000-08-31 15:10:24 +0000791 if (debug & DEBUG_COLLECTABLE) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000792 debug_cycle("collectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000793 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000794 if (tmod != NULL && (debug & DEBUG_STATS)) {
795 PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
796 if (f == NULL) {
797 PyErr_Clear();
798 }
799 else {
800 t1 = PyFloat_AsDouble(f)-t1;
801 Py_DECREF(f);
802 PySys_WriteStderr("gc: %.4fs elapsed.\n", t1);
803 }
804 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000805 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000806
807 /* Clear weakrefs and invoke callbacks as necessary. */
808 m += handle_weakrefs(&unreachable, old);
809
Tim Petersfb2ab4d2003-04-07 22:41:24 +0000810 /* Call tp_clear on objects in the unreachable set. This will cause
811 * the reference cycles to be broken. It may also cause some objects
812 * in finalizers to be freed.
813 */
Tim Petersf6b80452003-04-07 19:21:15 +0000814 delete_garbage(&unreachable, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000815
816 /* Collect statistics on uncollectable objects found and print
817 * debugging information. */
Tim Peters50c61d52003-04-06 01:50:50 +0000818 for (gc = finalizers.gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000819 gc != &finalizers;
820 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000821 n++;
Tim Petersbf384c22003-04-06 00:11:39 +0000822 if (debug & DEBUG_UNCOLLECTABLE)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000823 debug_cycle("uncollectable", FROM_GC(gc));
Tim Petersbf384c22003-04-06 00:11:39 +0000824 }
Jeremy Hylton06257772000-08-31 15:10:24 +0000825 if (debug & DEBUG_STATS) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000826 if (m == 0 && n == 0)
Jeremy Hylton06257772000-08-31 15:10:24 +0000827 PySys_WriteStderr("gc: done.\n");
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000828 else
Neal Norwitze22373d2006-03-06 23:31:56 +0000829 PySys_WriteStderr(
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830 "gc: done, "
831 "%" PY_FORMAT_SIZE_T "d unreachable, "
832 "%" PY_FORMAT_SIZE_T "d uncollectable.\n",
Neal Norwitze22373d2006-03-06 23:31:56 +0000833 n+m, n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000834 }
835
836 /* Append instances in the uncollectable set to a Python
837 * reachable list of garbage. The programmer has to deal with
Tim Petersbf384c22003-04-06 00:11:39 +0000838 * this if they insist on creating this type of structure.
839 */
Tim Petersf6b80452003-04-07 19:21:15 +0000840 (void)handle_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000841
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000842 if (PyErr_Occurred()) {
Tim Petersf6b80452003-04-07 19:21:15 +0000843 if (gc_str == NULL)
Neal Norwitz53cbdaa2007-08-23 21:42:55 +0000844 gc_str = PyUnicode_FromString("garbage collection");
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000845 PyErr_WriteUnraisable(gc_str);
846 Py_FatalError("unexpected exception during garbage collection");
847 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000848 return n+m;
849}
850
Neal Norwitz7b216c52006-03-04 20:01:53 +0000851static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000852collect_generations(void)
853{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000854 int i;
Neal Norwitz7b216c52006-03-04 20:01:53 +0000855 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000856
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000857 /* Find the oldest generation (higest numbered) where the count
858 * exceeds the threshold. Objects in the that generation and
859 * generations younger than it will be collected. */
860 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
861 if (generations[i].count > generations[i].threshold) {
862 n = collect(i);
863 break;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000864 }
865 }
866 return n;
867}
868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000869PyDoc_STRVAR(gc_enable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000870"enable() -> None\n"
871"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000872"Enable automatic garbage collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000873
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000874static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000875gc_enable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000876{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000877 enabled = 1;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000878 Py_INCREF(Py_None);
879 return Py_None;
880}
881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000882PyDoc_STRVAR(gc_disable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000883"disable() -> None\n"
884"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000885"Disable automatic garbage collection.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000886
887static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000888gc_disable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000889{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000890 enabled = 0;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000891 Py_INCREF(Py_None);
892 return Py_None;
893}
894
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000895PyDoc_STRVAR(gc_isenabled__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000896"isenabled() -> status\n"
897"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000898"Returns true if automatic garbage collection is enabled.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000899
900static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000901gc_isenabled(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000902{
Raymond Hettinger674d56b2004-01-04 04:00:13 +0000903 return PyBool_FromLong((long)enabled);
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000904}
905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000906PyDoc_STRVAR(gc_collect__doc__,
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000907"collect([generation]) -> n\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000908"\n"
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000909"With no arguments, run a full collection. The optional argument\n"
910"may be an integer specifying which generation to collect. A ValueError\n"
911"is raised if the generation number is invalid.\n\n"
912"The number of unreachable objects is returned.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000913
914static PyObject *
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000915gc_collect(PyObject *self, PyObject *args, PyObject *kws)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000916{
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000917 static char *keywords[] = {"generation", NULL};
918 int genarg = NUM_GENERATIONS - 1;
Neal Norwitz7b216c52006-03-04 20:01:53 +0000919 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000920
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000921 if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
922 return NULL;
923
924 else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
925 PyErr_SetString(PyExc_ValueError, "invalid generation");
926 return NULL;
927 }
928
Tim Peters50c61d52003-04-06 01:50:50 +0000929 if (collecting)
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000930 n = 0; /* already collecting, don't do anything */
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000931 else {
932 collecting = 1;
Barry Warsawd3c38ff2006-03-07 09:46:03 +0000933 n = collect(genarg);
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000934 collecting = 0;
935 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000936
Christian Heimes217cfd12007-12-02 14:31:20 +0000937 return PyLong_FromSsize_t(n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000938}
939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000940PyDoc_STRVAR(gc_set_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000941"set_debug(flags) -> None\n"
942"\n"
943"Set the garbage collection debugging flags. Debugging information is\n"
944"written to sys.stderr.\n"
945"\n"
946"flags is an integer and can have the following bits turned on:\n"
947"\n"
948" DEBUG_STATS - Print statistics during collection.\n"
949" DEBUG_COLLECTABLE - Print collectable objects found.\n"
950" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000951" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000952" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000953
954static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000955gc_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000956{
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000957 if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000958 return NULL;
959
960 Py_INCREF(Py_None);
961 return Py_None;
962}
963
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000964PyDoc_STRVAR(gc_get_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000965"get_debug() -> flags\n"
966"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000967"Get the garbage collection debugging flags.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000968
969static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000970gc_get_debug(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000971{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000972 return Py_BuildValue("i", debug);
973}
974
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000975PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +0000976"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000977"\n"
978"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000979"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000980
981static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000982gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000983{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000984 int i;
985 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
986 &generations[0].threshold,
987 &generations[1].threshold,
988 &generations[2].threshold))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000989 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000990 for (i = 2; i < NUM_GENERATIONS; i++) {
991 /* generations higher than 2 get the same threshold */
992 generations[i].threshold = generations[2].threshold;
993 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000994
995 Py_INCREF(Py_None);
996 return Py_None;
997}
998
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000999PyDoc_STRVAR(gc_get_thresh__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001000"get_threshold() -> (threshold0, threshold1, threshold2)\n"
1001"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001002"Return the current collection thresholds\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001003
1004static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001005gc_get_thresh(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001006{
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001007 return Py_BuildValue("(iii)",
1008 generations[0].threshold,
1009 generations[1].threshold,
1010 generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001011}
1012
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001013PyDoc_STRVAR(gc_get_count__doc__,
1014"get_count() -> (count0, count1, count2)\n"
1015"\n"
1016"Return the current collection counts\n");
1017
1018static PyObject *
1019gc_get_count(PyObject *self, PyObject *noargs)
1020{
1021 return Py_BuildValue("(iii)",
1022 generations[0].count,
1023 generations[1].count,
1024 generations[2].count);
1025}
1026
Neil Schemenauer48c70342001-08-09 15:38:31 +00001027static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001028referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001029{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001030 Py_ssize_t i;
Martin v. Löwisc8fe77b2001-11-29 18:08:31 +00001031 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1032 if (PyTuple_GET_ITEM(objs, i) == obj)
1033 return 1;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001034 return 0;
1035}
1036
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001037static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001038gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001039{
1040 PyGC_Head *gc;
1041 PyObject *obj;
1042 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +00001043 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +00001044 obj = FROM_GC(gc);
Christian Heimes90aa7642007-12-19 02:45:37 +00001045 traverse = Py_TYPE(obj)->tp_traverse;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001046 if (obj == objs || obj == resultlist)
1047 continue;
Martin v. Löwis560da622001-11-24 09:24:51 +00001048 if (traverse(obj, (visitproc)referrersvisit, objs)) {
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001049 if (PyList_Append(resultlist, obj) < 0)
1050 return 0; /* error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001051 }
1052 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001053 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001054}
1055
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001056PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001057"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001058Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001059
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001060static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001061gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001062{
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001063 int i;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001064 PyObject *result = PyList_New(0);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001065 if (!result) return NULL;
1066
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001067 for (i = 0; i < NUM_GENERATIONS; i++) {
1068 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1069 Py_DECREF(result);
1070 return NULL;
1071 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001072 }
Neil Schemenauer48c70342001-08-09 15:38:31 +00001073 return result;
1074}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001075
Tim Peters0f81ab62003-04-08 16:39:48 +00001076/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001077static int
Tim Peters730f5532003-04-08 17:17:17 +00001078referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001079{
Tim Peters0f81ab62003-04-08 16:39:48 +00001080 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001081}
1082
Tim Peters730f5532003-04-08 17:17:17 +00001083PyDoc_STRVAR(gc_get_referents__doc__,
1084"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001085Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001086
1087static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001088gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001089{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001090 Py_ssize_t i;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001091 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001092
1093 if (result == NULL)
1094 return NULL;
1095
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001096 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
Tim Peters0f81ab62003-04-08 16:39:48 +00001097 traverseproc traverse;
Tim Peters93ad66d2003-04-05 17:15:44 +00001098 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001099
1100 if (! PyObject_IS_GC(obj))
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001101 continue;
Christian Heimes90aa7642007-12-19 02:45:37 +00001102 traverse = Py_TYPE(obj)->tp_traverse;
Tim Peters0f81ab62003-04-08 16:39:48 +00001103 if (! traverse)
1104 continue;
Tim Peters730f5532003-04-08 17:17:17 +00001105 if (traverse(obj, (visitproc)referentsvisit, result)) {
Tim Peters0f81ab62003-04-08 16:39:48 +00001106 Py_DECREF(result);
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001107 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001108 }
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001109 }
1110 return result;
1111}
1112
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001113PyDoc_STRVAR(gc_get_objects__doc__,
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001114"get_objects() -> [...]\n"
1115"\n"
1116"Return a list of objects tracked by the collector (excluding the list\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001117"returned).\n");
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001118
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001119static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001120gc_get_objects(PyObject *self, PyObject *noargs)
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001121{
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001122 int i;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001123 PyObject* result;
1124
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001125 result = PyList_New(0);
Tim Peters50c61d52003-04-06 01:50:50 +00001126 if (result == NULL)
Martin v. Löwisf8a6f242001-12-02 18:31:02 +00001127 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001128 for (i = 0; i < NUM_GENERATIONS; i++) {
1129 if (append_objects(result, GEN_HEAD(i))) {
1130 Py_DECREF(result);
1131 return NULL;
1132 }
Martin v. Löwis155aad12001-12-02 12:21:34 +00001133 }
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001134 return result;
1135}
1136
1137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001139"This module provides access to the garbage collector for reference cycles.\n"
1140"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001141"enable() -- Enable automatic garbage collection.\n"
1142"disable() -- Disable automatic garbage collection.\n"
1143"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001144"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001145"get_count() -- Return the current collection counts.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001146"set_debug() -- Set debugging flags.\n"
1147"get_debug() -- Get debugging flags.\n"
1148"set_threshold() -- Set the collection thresholds.\n"
1149"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001150"get_objects() -- Return a list of all objects tracked by the collector.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001151"get_referrers() -- Return the list of objects that refer to an object.\n"
Tim Peters730f5532003-04-08 17:17:17 +00001152"get_referents() -- Return the list of objects that an object refers to.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001153
1154static PyMethodDef GcMethods[] = {
Tim Peters50c61d52003-04-06 01:50:50 +00001155 {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
1156 {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
1157 {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001158 {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +00001159 {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001160 {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001161 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +00001162 {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001163 {"collect", (PyCFunction)gc_collect,
1164 METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +00001165 {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
Martin v. Löwis560da622001-11-24 09:24:51 +00001166 {"get_referrers", gc_get_referrers, METH_VARARGS,
1167 gc_get_referrers__doc__},
Tim Peters730f5532003-04-08 17:17:17 +00001168 {"get_referents", gc_get_referents, METH_VARARGS,
1169 gc_get_referents__doc__},
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001170 {NULL, NULL} /* Sentinel */
1171};
1172
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001173PyMODINIT_FUNC
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001174initgc(void)
1175{
1176 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001177
1178 m = Py_InitModule4("gc",
1179 GcMethods,
1180 gc__doc__,
1181 NULL,
1182 PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00001183 if (m == NULL)
1184 return;
Tim Peters11558872003-04-06 23:30:52 +00001185
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001186 if (garbage == NULL) {
1187 garbage = PyList_New(0);
Tim Peters11558872003-04-06 23:30:52 +00001188 if (garbage == NULL)
1189 return;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001190 }
Neil Schemenauer3b1cbf92005-06-18 17:37:06 +00001191 Py_INCREF(garbage);
Tim Peters11558872003-04-06 23:30:52 +00001192 if (PyModule_AddObject(m, "garbage", garbage) < 0)
1193 return;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194
1195 /* Importing can't be done in collect() because collect()
1196 * can be called via PyGC_Collect() in Py_Finalize().
1197 * This wouldn't be a problem, except that <initialized> is
1198 * reset to 0 before calling collect which trips up
1199 * the import and triggers an assertion.
1200 */
1201 if (tmod == NULL) {
1202 tmod = PyImport_ImportModule("time");
1203 if (tmod == NULL)
1204 PyErr_Clear();
1205 }
1206
Tim Peters11558872003-04-06 23:30:52 +00001207#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return
1208 ADD_INT(DEBUG_STATS);
1209 ADD_INT(DEBUG_COLLECTABLE);
1210 ADD_INT(DEBUG_UNCOLLECTABLE);
Tim Peters11558872003-04-06 23:30:52 +00001211 ADD_INT(DEBUG_SAVEALL);
1212 ADD_INT(DEBUG_LEAK);
1213#undef ADD_INT
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001214}
1215
Guido van Rossume13ddc92003-04-17 17:29:22 +00001216/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001217Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001218PyGC_Collect(void)
1219{
Neal Norwitz7b216c52006-03-04 20:01:53 +00001220 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001221
1222 if (collecting)
1223 n = 0; /* already collecting, don't do anything */
1224 else {
1225 collecting = 1;
1226 n = collect(NUM_GENERATIONS - 1);
1227 collecting = 0;
1228 }
1229
1230 return n;
1231}
1232
Neil Schemenauer43411b52001-08-30 00:05:51 +00001233/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001234void
1235_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001236{
1237 _PyObject_Dump(FROM_GC(g));
1238}
1239
Neil Schemenauer43411b52001-08-30 00:05:51 +00001240/* extension modules might be compiled with GC support so these
1241 functions must always be available */
1242
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001243#undef PyObject_GC_Track
1244#undef PyObject_GC_UnTrack
1245#undef PyObject_GC_Del
1246#undef _PyObject_GC_Malloc
1247
Neil Schemenauer43411b52001-08-30 00:05:51 +00001248void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001249PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001250{
1251 _PyObject_GC_TRACK(op);
1252}
1253
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001254/* for binary compatibility with 2.2 */
Neil Schemenauer43411b52001-08-30 00:05:51 +00001255void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001256_PyObject_GC_Track(PyObject *op)
1257{
1258 PyObject_GC_Track(op);
1259}
1260
1261void
1262PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001263{
Tim Peters803526b2002-07-07 05:13:56 +00001264 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1265 * call PyObject_GC_UnTrack twice on an object.
1266 */
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001267 if (IS_TRACKED(op))
Guido van Rossumff413af2002-03-28 20:34:59 +00001268 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001269}
1270
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001271/* for binary compatibility with 2.2 */
1272void
1273_PyObject_GC_UnTrack(PyObject *op)
1274{
1275 PyObject_GC_UnTrack(op);
1276}
1277
Neil Schemenauer43411b52001-08-30 00:05:51 +00001278PyObject *
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001279_PyObject_GC_Malloc(size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001280{
1281 PyObject *op;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001282 PyGC_Head *g = (PyGC_Head *)PyObject_MALLOC(
1283 sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001284 if (g == NULL)
Jeremy Hylton8a135182002-06-06 23:23:55 +00001285 return PyErr_NoMemory();
Tim Petersea405632002-07-02 00:52:30 +00001286 g->gc.gc_refs = GC_UNTRACKED;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001287 generations[0].count++; /* number of allocated GC objects */
1288 if (generations[0].count > generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001289 enabled &&
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001290 generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001291 !collecting &&
1292 !PyErr_Occurred()) {
1293 collecting = 1;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001294 collect_generations();
Neil Schemenauer43411b52001-08-30 00:05:51 +00001295 collecting = 0;
1296 }
1297 op = FROM_GC(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001298 return op;
1299}
1300
1301PyObject *
1302_PyObject_GC_New(PyTypeObject *tp)
1303{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001304 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
Tim Petersfa8efab2002-04-28 01:57:25 +00001305 if (op != NULL)
1306 op = PyObject_INIT(op, tp);
1307 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001308}
1309
1310PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001311_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001312{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001313 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
1314 PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
Tim Petersfa8efab2002-04-28 01:57:25 +00001315 if (op != NULL)
1316 op = PyObject_INIT_VAR(op, tp, nitems);
1317 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001318}
1319
1320PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001321_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001322{
Christian Heimes90aa7642007-12-19 02:45:37 +00001323 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001324 PyGC_Head *g = AS_GC(op);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001325 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001326 if (g == NULL)
1327 return (PyVarObject *)PyErr_NoMemory();
1328 op = (PyVarObject *) FROM_GC(g);
Christian Heimes90aa7642007-12-19 02:45:37 +00001329 Py_SIZE(op) = nitems;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001330 return op;
1331}
1332
1333void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001334PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001335{
Neil Schemenauer43411b52001-08-30 00:05:51 +00001336 PyGC_Head *g = AS_GC(op);
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001337 if (IS_TRACKED(op))
Neil Schemenauer43411b52001-08-30 00:05:51 +00001338 gc_list_remove(g);
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001339 if (generations[0].count > 0) {
1340 generations[0].count--;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001341 }
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001342 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001343}
1344
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001345/* for binary compatibility with 2.2 */
1346#undef _PyObject_GC_Del
1347void
1348_PyObject_GC_Del(PyObject *op)
1349{
1350 PyObject_GC_Del(op);
1351}