blob: 36e53ec2ed8aa61d0a6910ede4e9f62e90fc3ea2 [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 */
69#define DEBUG_INSTANCES (1<<3) /* print instances */
70#define DEBUG_OBJECTS (1<<4) /* print other objects */
Neil Schemenauer544de1e2000-09-22 15:22:38 +000071#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000072#define DEBUG_LEAK DEBUG_COLLECTABLE | \
73 DEBUG_UNCOLLECTABLE | \
74 DEBUG_INSTANCES | \
Neil Schemenauer544de1e2000-09-22 15:22:38 +000075 DEBUG_OBJECTS | \
76 DEBUG_SAVEALL
Jeremy Hyltonb709df32000-09-01 02:47:25 +000077static int debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000078
Tim Peters6fc13d92002-07-02 18:12:35 +000079/*--------------------------------------------------------------------------
80gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +000081
Tim Peters6fc13d92002-07-02 18:12:35 +000082Between collections, every gc'ed object has one of two gc_refs values:
83
84GC_UNTRACKED
85 The initial state; objects returned by PyObject_GC_Malloc are in this
86 state. The object doesn't live in any generation list, and its
87 tp_traverse slot must not be called.
88
89GC_REACHABLE
90 The object lives in some generation list, and its tp_traverse is safe to
91 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
92 is called.
93
94During a collection, gc_refs can temporarily take on other states:
95
96>= 0
97 At the start of a collection, update_refs() copies the true refcount
98 to gc_refs, for each object in the generation being collected.
99 subtract_refs() then adjusts gc_refs so that it equals the number of
100 times an object is referenced directly from outside the generation
101 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +0000102 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000103
104GC_TENTATIVELY_UNREACHABLE
105 move_unreachable() then moves objects not reachable (whether directly or
106 indirectly) from outside the generation into an "unreachable" set.
107 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
108 again. Objects that are found to be unreachable have gc_refs set to
109 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
110 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
111 transition back to GC_REACHABLE.
112
113 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
114 for collection. If it's decided not to collect such an object (e.g.,
115 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
116----------------------------------------------------------------------------
117*/
Tim Petersea405632002-07-02 00:52:30 +0000118#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
119#define GC_REACHABLE _PyGC_REFS_REACHABLE
120#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000121
Tim Peters6fc13d92002-07-02 18:12:35 +0000122#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)
Tim Peters19b74c72002-07-01 03:52:19 +0000123#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)
124#define IS_TENTATIVELY_UNREACHABLE(o) ( \
125 (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000126
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000127/*** list functions ***/
128
129static void
130gc_list_init(PyGC_Head *list)
131{
Tim Peters9e4ca102001-10-11 18:31:31 +0000132 list->gc.gc_prev = list;
133 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000134}
135
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000136static int
137gc_list_is_empty(PyGC_Head *list)
138{
139 return (list->gc.gc_next == list);
140}
141
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}
150
151static void
152gc_list_remove(PyGC_Head *node)
153{
Tim Peters9e4ca102001-10-11 18:31:31 +0000154 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
155 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
156 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000157}
158
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000159/* append a list onto another list, from becomes an empty list */
160static void
161gc_list_merge(PyGC_Head *from, PyGC_Head *to)
162{
163 PyGC_Head *tail;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000164 if (!gc_list_is_empty(from)) {
Tim Peters9e4ca102001-10-11 18:31:31 +0000165 tail = to->gc.gc_prev;
166 tail->gc.gc_next = from->gc.gc_next;
167 tail->gc.gc_next->gc.gc_prev = tail;
168 to->gc.gc_prev = from->gc.gc_prev;
169 to->gc.gc_prev->gc.gc_next = to;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000170 }
171 gc_list_init(from);
172}
173
174static long
175gc_list_size(PyGC_Head *list)
176{
177 PyGC_Head *gc;
178 long n = 0;
Tim Peters9e4ca102001-10-11 18:31:31 +0000179 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000180 n++;
181 }
182 return n;
183}
184
Tim Peters259272b2003-04-06 19:41:39 +0000185/* Append objects in a GC list to a Python list.
186 * Return 0 if all OK, < 0 if error (out of memory for list).
187 */
188static int
189append_objects(PyObject *py_list, PyGC_Head *gc_list)
190{
191 PyGC_Head *gc;
192 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
193 PyObject *op = FROM_GC(gc);
194 if (op != py_list) {
195 if (PyList_Append(py_list, op)) {
196 return -1; /* exception */
197 }
198 }
199 }
200 return 0;
201}
202
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000203/*** end of list stuff ***/
204
205
Tim Peters19b74c72002-07-01 03:52:19 +0000206/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
207 * in containers, and is GC_REACHABLE for all tracked gc objects not in
208 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000209 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000210static void
211update_refs(PyGC_Head *containers)
212{
Tim Peters9e4ca102001-10-11 18:31:31 +0000213 PyGC_Head *gc = containers->gc.gc_next;
Tim Petersea405632002-07-02 00:52:30 +0000214 for (; gc != containers; gc = gc->gc.gc_next) {
215 assert(gc->gc.gc_refs == GC_REACHABLE);
Tim Peters9e4ca102001-10-11 18:31:31 +0000216 gc->gc.gc_refs = FROM_GC(gc)->ob_refcnt;
Tim Petersea405632002-07-02 00:52:30 +0000217 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000218}
219
Tim Peters19b74c72002-07-01 03:52:19 +0000220/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000221static int
222visit_decref(PyObject *op, void *data)
223{
Tim Peters93cd83e2002-06-30 21:31:03 +0000224 assert(op != NULL);
Tim Peters19b74c72002-07-01 03:52:19 +0000225 if (PyObject_IS_GC(op)) {
226 PyGC_Head *gc = AS_GC(op);
227 /* We're only interested in gc_refs for objects in the
228 * generation being collected, which can be recognized
229 * because only they have positive gc_refs.
230 */
Tim Petersaab713b2002-07-02 22:15:28 +0000231 assert(gc->gc.gc_refs != 0); /* else refcount was too small */
Tim Peters19b74c72002-07-01 03:52:19 +0000232 if (gc->gc.gc_refs > 0)
233 gc->gc.gc_refs--;
234 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000235 return 0;
236}
237
Tim Peters19b74c72002-07-01 03:52:19 +0000238/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
239 * for all objects in containers, and is GC_REACHABLE for all tracked gc
240 * objects not in containers. The ones with gc_refs > 0 are directly
241 * reachable from outside containers, and so can't be collected.
242 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000243static void
244subtract_refs(PyGC_Head *containers)
245{
246 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000247 PyGC_Head *gc = containers->gc.gc_next;
248 for (; gc != containers; gc=gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000249 traverse = FROM_GC(gc)->ob_type->tp_traverse;
250 (void) traverse(FROM_GC(gc),
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000251 (visitproc)visit_decref,
252 NULL);
253 }
254}
255
Tim Peters19b74c72002-07-01 03:52:19 +0000256/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000257static int
Tim Peters19b74c72002-07-01 03:52:19 +0000258visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000259{
Tim Petersea405632002-07-02 00:52:30 +0000260 if (PyObject_IS_GC(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000261 PyGC_Head *gc = AS_GC(op);
262 const int gc_refs = gc->gc.gc_refs;
263
264 if (gc_refs == 0) {
265 /* This is in move_unreachable's 'young' list, but
266 * the traversal hasn't yet gotten to it. All
267 * we need to do is tell move_unreachable that it's
268 * reachable.
269 */
270 gc->gc.gc_refs = 1;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000271 }
Tim Peters19b74c72002-07-01 03:52:19 +0000272 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
273 /* This had gc_refs = 0 when move_unreachable got
274 * to it, but turns out it's reachable after all.
275 * Move it back to move_unreachable's 'young' list,
276 * and move_unreachable will eventually get to it
277 * again.
278 */
279 gc_list_remove(gc);
280 gc_list_append(gc, reachable);
281 gc->gc.gc_refs = 1;
282 }
283 /* Else there's nothing to do.
284 * If gc_refs > 0, it must be in move_unreachable's 'young'
285 * list, and move_unreachable will eventually get to it.
286 * If gc_refs == GC_REACHABLE, it's either in some other
287 * generation so we don't care about it, or move_unreachable
Tim Peters6fc13d92002-07-02 18:12:35 +0000288 * already dealt with it.
Tim Petersea405632002-07-02 00:52:30 +0000289 * If gc_refs == GC_UNTRACKED, it must be ignored.
Tim Peters19b74c72002-07-01 03:52:19 +0000290 */
Tim Petersea405632002-07-02 00:52:30 +0000291 else {
292 assert(gc_refs > 0
293 || gc_refs == GC_REACHABLE
294 || gc_refs == GC_UNTRACKED);
295 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000296 }
297 return 0;
298}
299
Tim Peters19b74c72002-07-01 03:52:19 +0000300/* Move the unreachable objects from young to unreachable. After this,
301 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
302 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
303 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
304 * All objects in young after this are directly or indirectly reachable
305 * from outside the original young; and all objects in unreachable are
306 * not.
Tim Peters88396172002-06-30 17:56:40 +0000307 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000308static void
Tim Peters19b74c72002-07-01 03:52:19 +0000309move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000310{
Tim Peters19b74c72002-07-01 03:52:19 +0000311 PyGC_Head *gc = young->gc.gc_next;
312
313 /* Invariants: all objects "to the left" of us in young have gc_refs
314 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
315 * from outside the young list as it was at entry. All other objects
316 * from the original young "to the left" of us are in unreachable now,
317 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
318 * left of us in 'young' now have been scanned, and no objects here
319 * or to the right have been scanned yet.
320 */
321
322 while (gc != young) {
323 PyGC_Head *next;
324
Tim Peters6fc13d92002-07-02 18:12:35 +0000325 if (gc->gc.gc_refs) {
326 /* gc is definitely reachable from outside the
327 * original 'young'. Mark it as such, and traverse
328 * its pointers to find any other objects that may
329 * be directly reachable from it. Note that the
330 * call to tp_traverse may append objects to young,
331 * so we have to wait until it returns to determine
332 * the next object to visit.
333 */
334 PyObject *op = FROM_GC(gc);
335 traverseproc traverse = op->ob_type->tp_traverse;
336 assert(gc->gc.gc_refs > 0);
337 gc->gc.gc_refs = GC_REACHABLE;
338 (void) traverse(op,
339 (visitproc)visit_reachable,
340 (void *)young);
341 next = gc->gc.gc_next;
342 }
343 else {
Tim Peters19b74c72002-07-01 03:52:19 +0000344 /* This *may* be unreachable. To make progress,
345 * assume it is. gc isn't directly reachable from
346 * any object we've already traversed, but may be
347 * reachable from an object we haven't gotten to yet.
348 * visit_reachable will eventually move gc back into
349 * young if that's so, and we'll see it again.
350 */
351 next = gc->gc.gc_next;
352 gc_list_remove(gc);
353 gc_list_append(gc, unreachable);
354 gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
355 }
Tim Peters19b74c72002-07-01 03:52:19 +0000356 gc = next;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000357 }
358}
359
Tim Peters86b993b2003-04-05 17:35:54 +0000360/* Return true if object has a finalization method.
361 * CAUTION: An instance of an old-style class has to be checked for a
362 *__del__ method, and that can cause arbitrary Python code to get executed
363 * via the class's __getattr__ hook (if any). This function can therefore
364 * mutate the object graph, and that's been the source of subtle bugs.
365 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000366static int
367has_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000368{
Tim Peters86b993b2003-04-05 17:35:54 +0000369 if (PyInstance_Check(op)) {
370 /* This is the dangerous path: hasattr can invoke
371 * the class __getattr__(), and that can do anything.
372 */
373 assert(delstr != NULL);
374 return PyObject_HasAttr(op, delstr);
375 }
376 else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
377 return op->ob_type->tp_del != NULL;
378 else
379 return 0;
Neil Schemenauera765c122001-11-01 17:35:23 +0000380}
381
Tim Petersf6ae7a42003-04-05 18:40:50 +0000382/* Move all objects out of unreachable, into collectable or finalizers.
383 * It's possible that some objects will get collected (via refcount falling
384 * to 0), or resurrected, as a side effect of checking for __del__ methods.
385 * After, finalizers contains all the objects from unreachable that haven't
386 * been collected by magic, and that have a finalizer. gc_refs is
387 * GC_REACHABLE for all of those. collectable contains all the remaining
388 * objects from unreachable, and gc_refs remains GC_TENTATIVELY_UNREACHABLE
389 * for those (we're still not sure they're reclaimable after this! Some
390 * may yet by reachable *from* the objects in finalizers).
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000391 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000392static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000393move_finalizers(PyGC_Head *unreachable, PyGC_Head *collectable,
394 PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000395{
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000396 while (!gc_list_is_empty(unreachable)) {
397 PyGC_Head *gc = unreachable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000398 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000399 int finalizer;
400
Tim Petersf6ae7a42003-04-05 18:40:50 +0000401 assert(IS_TENTATIVELY_UNREACHABLE(op));
402
403 finalizer = has_finalizer(op);
404 if (unreachable->gc.gc_next == gc) {
405 gc_list_remove(gc);
406 if (finalizer) {
407 gc_list_append(gc, finalizers);
408 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000409 }
Tim Petersf6ae7a42003-04-05 18:40:50 +0000410 else
411 gc_list_append(gc, collectable);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000412 }
Tim Petersf6ae7a42003-04-05 18:40:50 +0000413 /* else has_finalizer() deleted op via side effect */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000414 }
415}
416
Tim Peters19b74c72002-07-01 03:52:19 +0000417/* A traversal callback for move_finalizer_reachable. */
418static int
419visit_move(PyObject *op, PyGC_Head *tolist)
420{
421 if (PyObject_IS_GC(op)) {
Tim Petersea405632002-07-02 00:52:30 +0000422 if (IS_TENTATIVELY_UNREACHABLE(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000423 PyGC_Head *gc = AS_GC(op);
424 gc_list_remove(gc);
425 gc_list_append(gc, tolist);
426 gc->gc.gc_refs = GC_REACHABLE;
427 }
428 }
429 return 0;
430}
431
432/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersbf384c22003-04-06 00:11:39 +0000433 * into the reachable_from_finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000434 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000435static void
Tim Petersbf384c22003-04-06 00:11:39 +0000436move_finalizer_reachable(PyGC_Head *finalizers,
437 PyGC_Head *reachable_from_finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000438{
439 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000440 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000441 for (; gc != finalizers; gc = gc->gc.gc_next) {
442 /* Note that the finalizers list may grow during this. */
Neil Schemenauer43411b52001-08-30 00:05:51 +0000443 traverse = FROM_GC(gc)->ob_type->tp_traverse;
Tim Peters88396172002-06-30 17:56:40 +0000444 (void) traverse(FROM_GC(gc),
Tim Petersbf384c22003-04-06 00:11:39 +0000445 (visitproc)visit_move,
446 (void *)reachable_from_finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000447 }
448}
449
450static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000451debug_instance(char *msg, PyInstanceObject *inst)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000452{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000453 char *cname;
Neil Schemenauera765c122001-11-01 17:35:23 +0000454 /* simple version of instance_repr */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000455 PyObject *classname = inst->in_class->cl_name;
456 if (classname != NULL && PyString_Check(classname))
457 cname = PyString_AsString(classname);
458 else
459 cname = "?";
Jeremy Hylton06257772000-08-31 15:10:24 +0000460 PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
461 msg, cname, inst);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000462}
463
464static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000465debug_cycle(char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000466{
467 if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000468 debug_instance(msg, (PyInstanceObject *)op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000469 }
470 else if (debug & DEBUG_OBJECTS) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000471 PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
472 msg, op->ob_type->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000473 }
474}
475
Tim Petersbf384c22003-04-06 00:11:39 +0000476/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
477 * only from such cycles).
Tim Peters259272b2003-04-06 19:41:39 +0000478 * If DEBUG_SAVEALL or hasfinalizer, the objects in finalizers are appended
479 * to the module garbage list (a Python list). The objects in finalizers
480 * are merged into the old list regardless.
481 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
482 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000483 */
Tim Peters259272b2003-04-06 19:41:39 +0000484static int
Tim Petersbf384c22003-04-06 00:11:39 +0000485handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old, int hasfinalizer)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000486{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000487 if (garbage == NULL) {
488 garbage = PyList_New(0);
Tim Petersbf384c22003-04-06 00:11:39 +0000489 if (garbage == NULL)
490 Py_FatalError("gc couldn't create gc.garbage list");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000491 }
Tim Peters259272b2003-04-06 19:41:39 +0000492 if ((debug & DEBUG_SAVEALL) || hasfinalizer) {
493 if (append_objects(garbage, finalizers) < 0)
494 return -1;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000495 }
Tim Peters259272b2003-04-06 19:41:39 +0000496 gc_list_merge(finalizers, old);
497 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000498}
499
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000500/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000501 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000502 * objects may be freed. It is possible I screwed something up here.
503 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000504static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000505delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000506{
507 inquiry clear;
508
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000509 while (!gc_list_is_empty(collectable)) {
510 PyGC_Head *gc = collectable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000511 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000512
Tim Peters19b74c72002-07-01 03:52:19 +0000513 assert(IS_TENTATIVELY_UNREACHABLE(op));
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000514 if (debug & DEBUG_SAVEALL) {
515 PyList_Append(garbage, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000516 }
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000517 else {
518 if ((clear = op->ob_type->tp_clear) != NULL) {
519 Py_INCREF(op);
Jeremy Hylton8a135182002-06-06 23:23:55 +0000520 clear(op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000521 Py_DECREF(op);
522 }
523 }
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000524 if (collectable->gc.gc_next == gc) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000525 /* object is still alive, move it, it may die later */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000526 gc_list_remove(gc);
527 gc_list_append(gc, old);
Tim Peters19b74c72002-07-01 03:52:19 +0000528 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000529 }
530 }
531}
532
533/* This is the main function. Read this to understand how the
534 * collection process works. */
535static long
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000536collect(int generation)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000537{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000538 int i;
Tim Peters19b74c72002-07-01 03:52:19 +0000539 long m = 0; /* # objects collected */
540 long n = 0; /* # unreachable objects that couldn't be collected */
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000541 PyGC_Head *young; /* the generation we are examining */
542 PyGC_Head *old; /* next older generation */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000543 PyGC_Head unreachable;
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000544 PyGC_Head collectable;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000545 PyGC_Head finalizers;
Tim Petersbf384c22003-04-06 00:11:39 +0000546 PyGC_Head reachable_from_finalizers;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000547 PyGC_Head *gc;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000548
Tim Peters93ad66d2003-04-05 17:15:44 +0000549 if (delstr == NULL) {
550 delstr = PyString_InternFromString("__del__");
551 if (delstr == NULL)
552 Py_FatalError("gc couldn't allocate \"__del__\"");
553 }
554
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000555 if (debug & DEBUG_STATS) {
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000556 PySys_WriteStderr("gc: collecting generation %d...\n",
557 generation);
558 PySys_WriteStderr("gc: objects in each generation:");
559 for (i = 0; i < NUM_GENERATIONS; i++) {
560 PySys_WriteStderr(" %ld", gc_list_size(GEN_HEAD(i)));
561 }
562 PySys_WriteStderr("\n");
563 }
564
565 /* update collection and allocation counters */
566 if (generation+1 < NUM_GENERATIONS)
567 generations[generation+1].count += 1;
568 for (i = 0; i <= generation; i++)
Neil Schemenauerc9051642002-06-28 19:16:04 +0000569 generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000570
571 /* merge younger generations with one we are currently collecting */
572 for (i = 0; i < generation; i++) {
573 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
574 }
575
576 /* handy references */
577 young = GEN_HEAD(generation);
Tim Peters19b74c72002-07-01 03:52:19 +0000578 if (generation < NUM_GENERATIONS-1)
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000579 old = GEN_HEAD(generation+1);
Tim Peters19b74c72002-07-01 03:52:19 +0000580 else
581 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000582
583 /* Using ob_refcnt and gc_refs, calculate which objects in the
584 * container set are reachable from outside the set (ie. have a
585 * refcount greater than 0 when all the references within the
Tim Peters19b74c72002-07-01 03:52:19 +0000586 * set are taken into account
587 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000588 update_refs(young);
589 subtract_refs(young);
590
Tim Peters19b74c72002-07-01 03:52:19 +0000591 /* Leave everything reachable from outside young in young, and move
592 * everything else (in young) to unreachable.
593 * NOTE: This used to move the reachable objects into a reachable
594 * set instead. But most things usually turn out to be reachable,
595 * so it's more efficient to move the unreachable things.
596 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000597 gc_list_init(&unreachable);
Tim Peters19b74c72002-07-01 03:52:19 +0000598 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000599
Tim Peters19b74c72002-07-01 03:52:19 +0000600 /* Move reachable objects to next generation. */
601 if (young != old)
602 gc_list_merge(young, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000603
Tim Peters19b74c72002-07-01 03:52:19 +0000604 /* All objects in unreachable are trash, but objects reachable from
605 * finalizers can't safely be deleted. Python programmers should take
606 * care not to create such things. For Python, finalizers means
607 * instance objects with __del__ methods.
Tim Peters93ad66d2003-04-05 17:15:44 +0000608 *
Tim Petersbf384c22003-04-06 00:11:39 +0000609 * Move each unreachable object into the collectable set or the
610 * finalizers set. Because we need to check for __del__ methods on
611 * instances of classic classes, arbitrary Python code may get
612 * executed by getattr hooks: that may resurrect or deallocate (via
613 * refcount falling to 0) unreachable objects, so this is very
614 * delicate.
Tim Peters19b74c72002-07-01 03:52:19 +0000615 */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000616 gc_list_init(&collectable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000617 gc_list_init(&finalizers);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000618 move_finalizers(&unreachable, &collectable, &finalizers);
Tim Petersbf384c22003-04-06 00:11:39 +0000619 /* finalizers contains the unreachable objects with a finalizer;
620 * unreachable objects reachable only *from* those are also
621 * uncollectable; we move those into a separate list
622 * (reachable_from_finalizers) so we don't have to do the dangerous
623 * has_finalizer() test again later.
624 */
625 gc_list_init(&reachable_from_finalizers);
626 move_finalizer_reachable(&finalizers, &reachable_from_finalizers);
627 /* And move everything only reachable from the reachable stuff. */
628 move_finalizer_reachable(&reachable_from_finalizers,
629 &reachable_from_finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000630
631 /* Collect statistics on collectable objects found and print
632 * debugging information. */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000633 for (gc = collectable.gc.gc_next; gc != &collectable;
Tim Peters9e4ca102001-10-11 18:31:31 +0000634 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000635 m++;
Jeremy Hylton06257772000-08-31 15:10:24 +0000636 if (debug & DEBUG_COLLECTABLE) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000637 debug_cycle("collectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000638 }
639 }
Tim Peters19b74c72002-07-01 03:52:19 +0000640 /* Call tp_clear on objects in the collectable set. This will cause
Tim Petersbf384c22003-04-06 00:11:39 +0000641 * the reference cycles to be broken. It may also cause some objects
642 * in finalizers and/or reachable_from_finalizers to be freed */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000643 delete_garbage(&collectable, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000644
645 /* Collect statistics on uncollectable objects found and print
646 * debugging information. */
Tim Peters50c61d52003-04-06 01:50:50 +0000647 for (gc = finalizers.gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000648 gc != &finalizers;
649 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000650 n++;
Tim Petersbf384c22003-04-06 00:11:39 +0000651 if (debug & DEBUG_UNCOLLECTABLE)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000652 debug_cycle("uncollectable", FROM_GC(gc));
Tim Petersbf384c22003-04-06 00:11:39 +0000653 }
654 for (gc = reachable_from_finalizers.gc.gc_next;
655 gc != &reachable_from_finalizers;
656 gc = gc->gc.gc_next) {
657 n++;
658 if (debug & DEBUG_UNCOLLECTABLE)
659 debug_cycle("uncollectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000660 }
Jeremy Hylton06257772000-08-31 15:10:24 +0000661 if (debug & DEBUG_STATS) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000662 if (m == 0 && n == 0) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000663 PySys_WriteStderr("gc: done.\n");
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000664 }
665 else {
Jeremy Hylton06257772000-08-31 15:10:24 +0000666 PySys_WriteStderr(
667 "gc: done, %ld unreachable, %ld uncollectable.\n",
668 n+m, n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000669 }
670 }
671
672 /* Append instances in the uncollectable set to a Python
673 * reachable list of garbage. The programmer has to deal with
Tim Petersbf384c22003-04-06 00:11:39 +0000674 * this if they insist on creating this type of structure.
675 */
Tim Peters259272b2003-04-06 19:41:39 +0000676 if (handle_finalizers(&finalizers, old, 1) == 0)
677 (void)handle_finalizers(&reachable_from_finalizers, old, 0);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000678
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000679 if (PyErr_Occurred()) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000680 if (gc_str == NULL) {
681 gc_str = PyString_FromString("garbage collection");
682 }
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000683 PyErr_WriteUnraisable(gc_str);
684 Py_FatalError("unexpected exception during garbage collection");
685 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000686 return n+m;
687}
688
689static long
690collect_generations(void)
691{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000692 int i;
Vladimir Marangozovb16714b2000-07-10 05:37:39 +0000693 long n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000694
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000695 /* Find the oldest generation (higest numbered) where the count
696 * exceeds the threshold. Objects in the that generation and
697 * generations younger than it will be collected. */
698 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
699 if (generations[i].count > generations[i].threshold) {
700 n = collect(i);
701 break;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000702 }
703 }
704 return n;
705}
706
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000707PyDoc_STRVAR(gc_enable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000708"enable() -> None\n"
709"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000710"Enable automatic garbage collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000711
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000712static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000713gc_enable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000714{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000715 enabled = 1;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000716 Py_INCREF(Py_None);
717 return Py_None;
718}
719
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000720PyDoc_STRVAR(gc_disable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000721"disable() -> None\n"
722"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000723"Disable automatic garbage collection.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000724
725static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000726gc_disable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000727{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000728 enabled = 0;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000729 Py_INCREF(Py_None);
730 return Py_None;
731}
732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000733PyDoc_STRVAR(gc_isenabled__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000734"isenabled() -> status\n"
735"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000736"Returns true if automatic garbage collection is enabled.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000737
738static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000739gc_isenabled(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000740{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000741 return Py_BuildValue("i", enabled);
742}
743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000744PyDoc_STRVAR(gc_collect__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000745"collect() -> n\n"
746"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000747"Run a full collection. The number of unreachable objects is returned.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000748
749static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000750gc_collect(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000751{
752 long n;
753
Tim Peters50c61d52003-04-06 01:50:50 +0000754 if (collecting)
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000755 n = 0; /* already collecting, don't do anything */
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000756 else {
757 collecting = 1;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000758 n = collect(NUM_GENERATIONS - 1);
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000759 collecting = 0;
760 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000761
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000762 return Py_BuildValue("l", n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000763}
764
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000765PyDoc_STRVAR(gc_set_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000766"set_debug(flags) -> None\n"
767"\n"
768"Set the garbage collection debugging flags. Debugging information is\n"
769"written to sys.stderr.\n"
770"\n"
771"flags is an integer and can have the following bits turned on:\n"
772"\n"
773" DEBUG_STATS - Print statistics during collection.\n"
774" DEBUG_COLLECTABLE - Print collectable objects found.\n"
775" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
776" DEBUG_INSTANCES - Print instance objects.\n"
777" DEBUG_OBJECTS - Print objects other than instances.\n"
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000778" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000779" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000780
781static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000782gc_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000783{
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000784 if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000785 return NULL;
786
787 Py_INCREF(Py_None);
788 return Py_None;
789}
790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000791PyDoc_STRVAR(gc_get_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000792"get_debug() -> flags\n"
793"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000794"Get the garbage collection debugging flags.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000795
796static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000797gc_get_debug(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000798{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000799 return Py_BuildValue("i", debug);
800}
801
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000802PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +0000803"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000804"\n"
805"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000806"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000807
808static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000809gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000810{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000811 int i;
812 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
813 &generations[0].threshold,
814 &generations[1].threshold,
815 &generations[2].threshold))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000816 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000817 for (i = 2; i < NUM_GENERATIONS; i++) {
818 /* generations higher than 2 get the same threshold */
819 generations[i].threshold = generations[2].threshold;
820 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000821
822 Py_INCREF(Py_None);
823 return Py_None;
824}
825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000826PyDoc_STRVAR(gc_get_thresh__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000827"get_threshold() -> (threshold0, threshold1, threshold2)\n"
828"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000829"Return the current collection thresholds\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000830
831static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000832gc_get_thresh(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000833{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000834 return Py_BuildValue("(iii)",
835 generations[0].threshold,
836 generations[1].threshold,
837 generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000838}
839
Neil Schemenauer48c70342001-08-09 15:38:31 +0000840static int
Martin v. Löwis560da622001-11-24 09:24:51 +0000841referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000842{
Martin v. Löwisc8fe77b2001-11-29 18:08:31 +0000843 int i;
844 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
845 if (PyTuple_GET_ITEM(objs, i) == obj)
846 return 1;
Neil Schemenauer48c70342001-08-09 15:38:31 +0000847 return 0;
848}
849
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000850static int
Martin v. Löwis560da622001-11-24 09:24:51 +0000851gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000852{
853 PyGC_Head *gc;
854 PyObject *obj;
855 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000856 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000857 obj = FROM_GC(gc);
Neil Schemenauer48c70342001-08-09 15:38:31 +0000858 traverse = obj->ob_type->tp_traverse;
859 if (obj == objs || obj == resultlist)
860 continue;
Martin v. Löwis560da622001-11-24 09:24:51 +0000861 if (traverse(obj, (visitproc)referrersvisit, objs)) {
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000862 if (PyList_Append(resultlist, obj) < 0)
863 return 0; /* error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000864 }
865 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000866 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000867}
868
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000869PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +0000870"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000871Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +0000872
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000873static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +0000874gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000875{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000876 int i;
Neil Schemenauer48c70342001-08-09 15:38:31 +0000877 PyObject *result = PyList_New(0);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000878 for (i = 0; i < NUM_GENERATIONS; i++) {
879 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
880 Py_DECREF(result);
881 return NULL;
882 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000883 }
Neil Schemenauer48c70342001-08-09 15:38:31 +0000884 return result;
885}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000886
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000887static int
888referrentsvisit(PyObject *obj, PyObject *list)
889{
890 if (PyList_Append(list, obj) < 0)
891 return 1;
892 return 0;
893}
894
895PyDoc_STRVAR(gc_get_referrents__doc__,
896"get_referrents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +0000897Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000898
899static PyObject *
900gc_get_referrents(PyObject *self, PyObject *args)
901{
902 int i;
903 PyObject *result = PyList_New(0);
904 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
Tim Peters93ad66d2003-04-05 17:15:44 +0000905 PyObject *obj = PyTuple_GET_ITEM(args, i);
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000906 traverseproc traverse = obj->ob_type->tp_traverse;
907 if (!traverse)
908 continue;
909 if (traverse(obj, (visitproc)referrentsvisit, result))
910 return NULL;
911 }
912 return result;
913}
914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000915PyDoc_STRVAR(gc_get_objects__doc__,
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000916"get_objects() -> [...]\n"
917"\n"
918"Return a list of objects tracked by the collector (excluding the list\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000919"returned).\n");
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000920
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000921static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000922gc_get_objects(PyObject *self, PyObject *noargs)
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000923{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000924 int i;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000925 PyObject* result;
926
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000927 result = PyList_New(0);
Tim Peters50c61d52003-04-06 01:50:50 +0000928 if (result == NULL)
Martin v. Löwisf8a6f242001-12-02 18:31:02 +0000929 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000930 for (i = 0; i < NUM_GENERATIONS; i++) {
931 if (append_objects(result, GEN_HEAD(i))) {
932 Py_DECREF(result);
933 return NULL;
934 }
Martin v. Löwis155aad12001-12-02 12:21:34 +0000935 }
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000936 return result;
937}
938
939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000940PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000941"This module provides access to the garbage collector for reference cycles.\n"
942"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000943"enable() -- Enable automatic garbage collection.\n"
944"disable() -- Disable automatic garbage collection.\n"
945"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000946"collect() -- Do a full collection right now.\n"
947"set_debug() -- Set debugging flags.\n"
948"get_debug() -- Get debugging flags.\n"
949"set_threshold() -- Set the collection thresholds.\n"
950"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000951"get_objects() -- Return a list of all objects tracked by the collector.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000952"get_referrers() -- Return the list of objects that refer to an object.\n"
953"get_referrents() -- Return the list of objects that an object refers to.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000954
955static PyMethodDef GcMethods[] = {
Tim Peters50c61d52003-04-06 01:50:50 +0000956 {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
957 {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
958 {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000959 {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +0000960 {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000961 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +0000962 {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
963 {"collect", gc_collect, METH_NOARGS, gc_collect__doc__},
964 {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
Martin v. Löwis560da622001-11-24 09:24:51 +0000965 {"get_referrers", gc_get_referrers, METH_VARARGS,
966 gc_get_referrers__doc__},
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000967 {"get_referrents", gc_get_referrents, METH_VARARGS,
968 gc_get_referrents__doc__},
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000969 {NULL, NULL} /* Sentinel */
970};
971
972void
973initgc(void)
974{
975 PyObject *m;
976 PyObject *d;
977
978 m = Py_InitModule4("gc",
979 GcMethods,
980 gc__doc__,
981 NULL,
982 PYTHON_API_VERSION);
983 d = PyModule_GetDict(m);
984 if (garbage == NULL) {
985 garbage = PyList_New(0);
986 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000987 PyDict_SetItemString(d, "garbage", garbage);
988 PyDict_SetItemString(d, "DEBUG_STATS",
989 PyInt_FromLong(DEBUG_STATS));
990 PyDict_SetItemString(d, "DEBUG_COLLECTABLE",
991 PyInt_FromLong(DEBUG_COLLECTABLE));
992 PyDict_SetItemString(d, "DEBUG_UNCOLLECTABLE",
993 PyInt_FromLong(DEBUG_UNCOLLECTABLE));
994 PyDict_SetItemString(d, "DEBUG_INSTANCES",
995 PyInt_FromLong(DEBUG_INSTANCES));
996 PyDict_SetItemString(d, "DEBUG_OBJECTS",
997 PyInt_FromLong(DEBUG_OBJECTS));
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000998 PyDict_SetItemString(d, "DEBUG_SAVEALL",
999 PyInt_FromLong(DEBUG_SAVEALL));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001000 PyDict_SetItemString(d, "DEBUG_LEAK",
1001 PyInt_FromLong(DEBUG_LEAK));
1002}
1003
Neil Schemenauer43411b52001-08-30 00:05:51 +00001004/* for debugging */
1005void _PyGC_Dump(PyGC_Head *g)
1006{
1007 _PyObject_Dump(FROM_GC(g));
1008}
1009
Neil Schemenauer43411b52001-08-30 00:05:51 +00001010/* extension modules might be compiled with GC support so these
1011 functions must always be available */
1012
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001013#undef PyObject_GC_Track
1014#undef PyObject_GC_UnTrack
1015#undef PyObject_GC_Del
1016#undef _PyObject_GC_Malloc
1017
Neil Schemenauer43411b52001-08-30 00:05:51 +00001018void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001019PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001020{
1021 _PyObject_GC_TRACK(op);
1022}
1023
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001024/* for binary compatibility with 2.2 */
Neil Schemenauer43411b52001-08-30 00:05:51 +00001025void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001026_PyObject_GC_Track(PyObject *op)
1027{
1028 PyObject_GC_Track(op);
1029}
1030
1031void
1032PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001033{
Tim Peters803526b2002-07-07 05:13:56 +00001034 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1035 * call PyObject_GC_UnTrack twice on an object.
1036 */
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001037 if (IS_TRACKED(op))
Guido van Rossumff413af2002-03-28 20:34:59 +00001038 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001039}
1040
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001041/* for binary compatibility with 2.2 */
1042void
1043_PyObject_GC_UnTrack(PyObject *op)
1044{
1045 PyObject_GC_UnTrack(op);
1046}
1047
Neil Schemenauer43411b52001-08-30 00:05:51 +00001048PyObject *
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001049_PyObject_GC_Malloc(size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001050{
1051 PyObject *op;
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001052 PyGC_Head *g = PyObject_MALLOC(sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001053 if (g == NULL)
Jeremy Hylton8a135182002-06-06 23:23:55 +00001054 return PyErr_NoMemory();
Tim Petersea405632002-07-02 00:52:30 +00001055 g->gc.gc_refs = GC_UNTRACKED;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001056 generations[0].count++; /* number of allocated GC objects */
1057 if (generations[0].count > generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001058 enabled &&
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001059 generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001060 !collecting &&
1061 !PyErr_Occurred()) {
1062 collecting = 1;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001063 collect_generations();
Neil Schemenauer43411b52001-08-30 00:05:51 +00001064 collecting = 0;
1065 }
1066 op = FROM_GC(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001067 return op;
1068}
1069
1070PyObject *
1071_PyObject_GC_New(PyTypeObject *tp)
1072{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001073 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
Tim Petersfa8efab2002-04-28 01:57:25 +00001074 if (op != NULL)
1075 op = PyObject_INIT(op, tp);
1076 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001077}
1078
1079PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +00001080_PyObject_GC_NewVar(PyTypeObject *tp, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001081{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001082 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
1083 PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
Tim Petersfa8efab2002-04-28 01:57:25 +00001084 if (op != NULL)
1085 op = PyObject_INIT_VAR(op, tp, nitems);
1086 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001087}
1088
1089PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +00001090_PyObject_GC_Resize(PyVarObject *op, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001091{
Tim Petersf2a67da2001-10-07 03:54:51 +00001092 const size_t basicsize = _PyObject_VAR_SIZE(op->ob_type, nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001093 PyGC_Head *g = AS_GC(op);
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001094 g = PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001095 if (g == NULL)
1096 return (PyVarObject *)PyErr_NoMemory();
1097 op = (PyVarObject *) FROM_GC(g);
Tim Peters6d483d32001-10-06 21:27:34 +00001098 op->ob_size = nitems;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001099 return op;
1100}
1101
1102void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001103PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001104{
Neil Schemenauer43411b52001-08-30 00:05:51 +00001105 PyGC_Head *g = AS_GC(op);
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001106 if (IS_TRACKED(op))
Neil Schemenauer43411b52001-08-30 00:05:51 +00001107 gc_list_remove(g);
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001108 if (generations[0].count > 0) {
1109 generations[0].count--;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001110 }
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001111 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001112}
1113
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001114/* for binary compatibility with 2.2 */
1115#undef _PyObject_GC_Del
1116void
1117_PyObject_GC_Del(PyObject *op)
1118{
1119 PyObject_GC_Del(op);
1120}