blob: 1bb065b1c221ed155cc5fad84888519ea9308051 [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
185/*** end of list stuff ***/
186
187
Tim Peters19b74c72002-07-01 03:52:19 +0000188/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
189 * in containers, and is GC_REACHABLE for all tracked gc objects not in
190 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000191 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000192static void
193update_refs(PyGC_Head *containers)
194{
Tim Peters9e4ca102001-10-11 18:31:31 +0000195 PyGC_Head *gc = containers->gc.gc_next;
Tim Petersea405632002-07-02 00:52:30 +0000196 for (; gc != containers; gc = gc->gc.gc_next) {
197 assert(gc->gc.gc_refs == GC_REACHABLE);
Tim Peters9e4ca102001-10-11 18:31:31 +0000198 gc->gc.gc_refs = FROM_GC(gc)->ob_refcnt;
Tim Petersea405632002-07-02 00:52:30 +0000199 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000200}
201
Tim Peters19b74c72002-07-01 03:52:19 +0000202/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000203static int
204visit_decref(PyObject *op, void *data)
205{
Tim Peters93cd83e2002-06-30 21:31:03 +0000206 assert(op != NULL);
Tim Peters19b74c72002-07-01 03:52:19 +0000207 if (PyObject_IS_GC(op)) {
208 PyGC_Head *gc = AS_GC(op);
209 /* We're only interested in gc_refs for objects in the
210 * generation being collected, which can be recognized
211 * because only they have positive gc_refs.
212 */
Tim Petersaab713b2002-07-02 22:15:28 +0000213 assert(gc->gc.gc_refs != 0); /* else refcount was too small */
Tim Peters19b74c72002-07-01 03:52:19 +0000214 if (gc->gc.gc_refs > 0)
215 gc->gc.gc_refs--;
216 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000217 return 0;
218}
219
Tim Peters19b74c72002-07-01 03:52:19 +0000220/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
221 * for all objects in containers, and is GC_REACHABLE for all tracked gc
222 * objects not in containers. The ones with gc_refs > 0 are directly
223 * reachable from outside containers, and so can't be collected.
224 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000225static void
226subtract_refs(PyGC_Head *containers)
227{
228 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000229 PyGC_Head *gc = containers->gc.gc_next;
230 for (; gc != containers; gc=gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000231 traverse = FROM_GC(gc)->ob_type->tp_traverse;
232 (void) traverse(FROM_GC(gc),
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000233 (visitproc)visit_decref,
234 NULL);
235 }
236}
237
Tim Peters19b74c72002-07-01 03:52:19 +0000238/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000239static int
Tim Peters19b74c72002-07-01 03:52:19 +0000240visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000241{
Tim Petersea405632002-07-02 00:52:30 +0000242 if (PyObject_IS_GC(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000243 PyGC_Head *gc = AS_GC(op);
244 const int gc_refs = gc->gc.gc_refs;
245
246 if (gc_refs == 0) {
247 /* This is in move_unreachable's 'young' list, but
248 * the traversal hasn't yet gotten to it. All
249 * we need to do is tell move_unreachable that it's
250 * reachable.
251 */
252 gc->gc.gc_refs = 1;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000253 }
Tim Peters19b74c72002-07-01 03:52:19 +0000254 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
255 /* This had gc_refs = 0 when move_unreachable got
256 * to it, but turns out it's reachable after all.
257 * Move it back to move_unreachable's 'young' list,
258 * and move_unreachable will eventually get to it
259 * again.
260 */
261 gc_list_remove(gc);
262 gc_list_append(gc, reachable);
263 gc->gc.gc_refs = 1;
264 }
265 /* Else there's nothing to do.
266 * If gc_refs > 0, it must be in move_unreachable's 'young'
267 * list, and move_unreachable will eventually get to it.
268 * If gc_refs == GC_REACHABLE, it's either in some other
269 * generation so we don't care about it, or move_unreachable
Tim Peters6fc13d92002-07-02 18:12:35 +0000270 * already dealt with it.
Tim Petersea405632002-07-02 00:52:30 +0000271 * If gc_refs == GC_UNTRACKED, it must be ignored.
Tim Peters19b74c72002-07-01 03:52:19 +0000272 */
Tim Petersea405632002-07-02 00:52:30 +0000273 else {
274 assert(gc_refs > 0
275 || gc_refs == GC_REACHABLE
276 || gc_refs == GC_UNTRACKED);
277 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000278 }
279 return 0;
280}
281
Tim Peters19b74c72002-07-01 03:52:19 +0000282/* Move the unreachable objects from young to unreachable. After this,
283 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
284 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
285 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
286 * All objects in young after this are directly or indirectly reachable
287 * from outside the original young; and all objects in unreachable are
288 * not.
Tim Peters88396172002-06-30 17:56:40 +0000289 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000290static void
Tim Peters19b74c72002-07-01 03:52:19 +0000291move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000292{
Tim Peters19b74c72002-07-01 03:52:19 +0000293 PyGC_Head *gc = young->gc.gc_next;
294
295 /* Invariants: all objects "to the left" of us in young have gc_refs
296 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
297 * from outside the young list as it was at entry. All other objects
298 * from the original young "to the left" of us are in unreachable now,
299 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
300 * left of us in 'young' now have been scanned, and no objects here
301 * or to the right have been scanned yet.
302 */
303
304 while (gc != young) {
305 PyGC_Head *next;
306
Tim Peters6fc13d92002-07-02 18:12:35 +0000307 if (gc->gc.gc_refs) {
308 /* gc is definitely reachable from outside the
309 * original 'young'. Mark it as such, and traverse
310 * its pointers to find any other objects that may
311 * be directly reachable from it. Note that the
312 * call to tp_traverse may append objects to young,
313 * so we have to wait until it returns to determine
314 * the next object to visit.
315 */
316 PyObject *op = FROM_GC(gc);
317 traverseproc traverse = op->ob_type->tp_traverse;
318 assert(gc->gc.gc_refs > 0);
319 gc->gc.gc_refs = GC_REACHABLE;
320 (void) traverse(op,
321 (visitproc)visit_reachable,
322 (void *)young);
323 next = gc->gc.gc_next;
324 }
325 else {
Tim Peters19b74c72002-07-01 03:52:19 +0000326 /* This *may* be unreachable. To make progress,
327 * assume it is. gc isn't directly reachable from
328 * any object we've already traversed, but may be
329 * reachable from an object we haven't gotten to yet.
330 * visit_reachable will eventually move gc back into
331 * young if that's so, and we'll see it again.
332 */
333 next = gc->gc.gc_next;
334 gc_list_remove(gc);
335 gc_list_append(gc, unreachable);
336 gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
337 }
Tim Peters19b74c72002-07-01 03:52:19 +0000338 gc = next;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000339 }
340}
341
Tim Peters86b993b2003-04-05 17:35:54 +0000342/* Return true if object has a finalization method.
343 * CAUTION: An instance of an old-style class has to be checked for a
344 *__del__ method, and that can cause arbitrary Python code to get executed
345 * via the class's __getattr__ hook (if any). This function can therefore
346 * mutate the object graph, and that's been the source of subtle bugs.
347 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000348static int
349has_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000350{
Tim Peters86b993b2003-04-05 17:35:54 +0000351 if (PyInstance_Check(op)) {
352 /* This is the dangerous path: hasattr can invoke
353 * the class __getattr__(), and that can do anything.
354 */
355 assert(delstr != NULL);
356 return PyObject_HasAttr(op, delstr);
357 }
358 else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
359 return op->ob_type->tp_del != NULL;
360 else
361 return 0;
Neil Schemenauera765c122001-11-01 17:35:23 +0000362}
363
Tim Petersf6ae7a42003-04-05 18:40:50 +0000364/* Move all objects out of unreachable, into collectable or finalizers.
365 * It's possible that some objects will get collected (via refcount falling
366 * to 0), or resurrected, as a side effect of checking for __del__ methods.
367 * After, finalizers contains all the objects from unreachable that haven't
368 * been collected by magic, and that have a finalizer. gc_refs is
369 * GC_REACHABLE for all of those. collectable contains all the remaining
370 * objects from unreachable, and gc_refs remains GC_TENTATIVELY_UNREACHABLE
371 * for those (we're still not sure they're reclaimable after this! Some
372 * may yet by reachable *from* the objects in finalizers).
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000373 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000374static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000375move_finalizers(PyGC_Head *unreachable, PyGC_Head *collectable,
376 PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000377{
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000378 while (!gc_list_is_empty(unreachable)) {
379 PyGC_Head *gc = unreachable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000380 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000381 int finalizer;
382
Tim Petersf6ae7a42003-04-05 18:40:50 +0000383 assert(IS_TENTATIVELY_UNREACHABLE(op));
384
385 finalizer = has_finalizer(op);
386 if (unreachable->gc.gc_next == gc) {
387 gc_list_remove(gc);
388 if (finalizer) {
389 gc_list_append(gc, finalizers);
390 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000391 }
Tim Petersf6ae7a42003-04-05 18:40:50 +0000392 else
393 gc_list_append(gc, collectable);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000394 }
Tim Petersf6ae7a42003-04-05 18:40:50 +0000395 /* else has_finalizer() deleted op via side effect */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000396 }
397}
398
Tim Peters19b74c72002-07-01 03:52:19 +0000399/* A traversal callback for move_finalizer_reachable. */
400static int
401visit_move(PyObject *op, PyGC_Head *tolist)
402{
403 if (PyObject_IS_GC(op)) {
Tim Petersea405632002-07-02 00:52:30 +0000404 if (IS_TENTATIVELY_UNREACHABLE(op)) {
Tim Peters19b74c72002-07-01 03:52:19 +0000405 PyGC_Head *gc = AS_GC(op);
406 gc_list_remove(gc);
407 gc_list_append(gc, tolist);
408 gc->gc.gc_refs = GC_REACHABLE;
409 }
410 }
411 return 0;
412}
413
414/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersbf384c22003-04-06 00:11:39 +0000415 * into the reachable_from_finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000416 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000417static void
Tim Petersbf384c22003-04-06 00:11:39 +0000418move_finalizer_reachable(PyGC_Head *finalizers,
419 PyGC_Head *reachable_from_finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000420{
421 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000422 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000423 for (; gc != finalizers; gc = gc->gc.gc_next) {
424 /* Note that the finalizers list may grow during this. */
Neil Schemenauer43411b52001-08-30 00:05:51 +0000425 traverse = FROM_GC(gc)->ob_type->tp_traverse;
Tim Peters88396172002-06-30 17:56:40 +0000426 (void) traverse(FROM_GC(gc),
Tim Petersbf384c22003-04-06 00:11:39 +0000427 (visitproc)visit_move,
428 (void *)reachable_from_finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000429 }
430}
431
432static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000433debug_instance(char *msg, PyInstanceObject *inst)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000434{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000435 char *cname;
Neil Schemenauera765c122001-11-01 17:35:23 +0000436 /* simple version of instance_repr */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000437 PyObject *classname = inst->in_class->cl_name;
438 if (classname != NULL && PyString_Check(classname))
439 cname = PyString_AsString(classname);
440 else
441 cname = "?";
Jeremy Hylton06257772000-08-31 15:10:24 +0000442 PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
443 msg, cname, inst);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000444}
445
446static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000447debug_cycle(char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000448{
449 if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000450 debug_instance(msg, (PyInstanceObject *)op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000451 }
452 else if (debug & DEBUG_OBJECTS) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000453 PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
454 msg, op->ob_type->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000455 }
456}
457
Tim Petersbf384c22003-04-06 00:11:39 +0000458/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
459 * only from such cycles).
460 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000461static void
Tim Petersbf384c22003-04-06 00:11:39 +0000462handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old, int hasfinalizer)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000463{
464 PyGC_Head *gc;
465 if (garbage == NULL) {
466 garbage = PyList_New(0);
Tim Petersbf384c22003-04-06 00:11:39 +0000467 if (garbage == NULL)
468 Py_FatalError("gc couldn't create gc.garbage list");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000469 }
Tim Petersbf384c22003-04-06 00:11:39 +0000470 for (gc = finalizers->gc.gc_next;
471 gc != finalizers;
472 gc = finalizers->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000473 PyObject *op = FROM_GC(gc);
Tim Petersbf384c22003-04-06 00:11:39 +0000474
475 assert(IS_REACHABLE(op));
476 if ((debug & DEBUG_SAVEALL) || hasfinalizer) {
Neil Schemenauera765c122001-11-01 17:35:23 +0000477 /* If SAVEALL is not set then just append objects with
478 * finalizers to the list of garbage. All objects in
479 * the finalizers list are reachable from those
Tim Peters19b74c72002-07-01 03:52:19 +0000480 * objects.
481 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000482 PyList_Append(garbage, op);
483 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000484 gc_list_remove(gc);
485 gc_list_append(gc, old);
486 }
487}
488
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000489/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000490 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000491 * objects may be freed. It is possible I screwed something up here.
492 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000493static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000494delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000495{
496 inquiry clear;
497
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000498 while (!gc_list_is_empty(collectable)) {
499 PyGC_Head *gc = collectable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000500 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000501
Tim Peters19b74c72002-07-01 03:52:19 +0000502 assert(IS_TENTATIVELY_UNREACHABLE(op));
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000503 if (debug & DEBUG_SAVEALL) {
504 PyList_Append(garbage, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000505 }
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000506 else {
507 if ((clear = op->ob_type->tp_clear) != NULL) {
508 Py_INCREF(op);
Jeremy Hylton8a135182002-06-06 23:23:55 +0000509 clear(op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000510 Py_DECREF(op);
511 }
512 }
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000513 if (collectable->gc.gc_next == gc) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000514 /* object is still alive, move it, it may die later */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000515 gc_list_remove(gc);
516 gc_list_append(gc, old);
Tim Peters19b74c72002-07-01 03:52:19 +0000517 gc->gc.gc_refs = GC_REACHABLE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000518 }
519 }
520}
521
522/* This is the main function. Read this to understand how the
523 * collection process works. */
524static long
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000525collect(int generation)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000526{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000527 int i;
Tim Peters19b74c72002-07-01 03:52:19 +0000528 long m = 0; /* # objects collected */
529 long n = 0; /* # unreachable objects that couldn't be collected */
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000530 PyGC_Head *young; /* the generation we are examining */
531 PyGC_Head *old; /* next older generation */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000532 PyGC_Head unreachable;
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000533 PyGC_Head collectable;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000534 PyGC_Head finalizers;
Tim Petersbf384c22003-04-06 00:11:39 +0000535 PyGC_Head reachable_from_finalizers;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000536 PyGC_Head *gc;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000537
Tim Peters93ad66d2003-04-05 17:15:44 +0000538 if (delstr == NULL) {
539 delstr = PyString_InternFromString("__del__");
540 if (delstr == NULL)
541 Py_FatalError("gc couldn't allocate \"__del__\"");
542 }
543
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000544 if (debug & DEBUG_STATS) {
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000545 PySys_WriteStderr("gc: collecting generation %d...\n",
546 generation);
547 PySys_WriteStderr("gc: objects in each generation:");
548 for (i = 0; i < NUM_GENERATIONS; i++) {
549 PySys_WriteStderr(" %ld", gc_list_size(GEN_HEAD(i)));
550 }
551 PySys_WriteStderr("\n");
552 }
553
554 /* update collection and allocation counters */
555 if (generation+1 < NUM_GENERATIONS)
556 generations[generation+1].count += 1;
557 for (i = 0; i <= generation; i++)
Neil Schemenauerc9051642002-06-28 19:16:04 +0000558 generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000559
560 /* merge younger generations with one we are currently collecting */
561 for (i = 0; i < generation; i++) {
562 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
563 }
564
565 /* handy references */
566 young = GEN_HEAD(generation);
Tim Peters19b74c72002-07-01 03:52:19 +0000567 if (generation < NUM_GENERATIONS-1)
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000568 old = GEN_HEAD(generation+1);
Tim Peters19b74c72002-07-01 03:52:19 +0000569 else
570 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000571
572 /* Using ob_refcnt and gc_refs, calculate which objects in the
573 * container set are reachable from outside the set (ie. have a
574 * refcount greater than 0 when all the references within the
Tim Peters19b74c72002-07-01 03:52:19 +0000575 * set are taken into account
576 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000577 update_refs(young);
578 subtract_refs(young);
579
Tim Peters19b74c72002-07-01 03:52:19 +0000580 /* Leave everything reachable from outside young in young, and move
581 * everything else (in young) to unreachable.
582 * NOTE: This used to move the reachable objects into a reachable
583 * set instead. But most things usually turn out to be reachable,
584 * so it's more efficient to move the unreachable things.
585 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000586 gc_list_init(&unreachable);
Tim Peters19b74c72002-07-01 03:52:19 +0000587 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000588
Tim Peters19b74c72002-07-01 03:52:19 +0000589 /* Move reachable objects to next generation. */
590 if (young != old)
591 gc_list_merge(young, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000592
Tim Peters19b74c72002-07-01 03:52:19 +0000593 /* All objects in unreachable are trash, but objects reachable from
594 * finalizers can't safely be deleted. Python programmers should take
595 * care not to create such things. For Python, finalizers means
596 * instance objects with __del__ methods.
Tim Peters93ad66d2003-04-05 17:15:44 +0000597 *
Tim Petersbf384c22003-04-06 00:11:39 +0000598 * Move each unreachable object into the collectable set or the
599 * finalizers set. Because we need to check for __del__ methods on
600 * instances of classic classes, arbitrary Python code may get
601 * executed by getattr hooks: that may resurrect or deallocate (via
602 * refcount falling to 0) unreachable objects, so this is very
603 * delicate.
Tim Peters19b74c72002-07-01 03:52:19 +0000604 */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000605 gc_list_init(&collectable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000606 gc_list_init(&finalizers);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000607 move_finalizers(&unreachable, &collectable, &finalizers);
Tim Petersbf384c22003-04-06 00:11:39 +0000608 /* finalizers contains the unreachable objects with a finalizer;
609 * unreachable objects reachable only *from* those are also
610 * uncollectable; we move those into a separate list
611 * (reachable_from_finalizers) so we don't have to do the dangerous
612 * has_finalizer() test again later.
613 */
614 gc_list_init(&reachable_from_finalizers);
615 move_finalizer_reachable(&finalizers, &reachable_from_finalizers);
616 /* And move everything only reachable from the reachable stuff. */
617 move_finalizer_reachable(&reachable_from_finalizers,
618 &reachable_from_finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000619
620 /* Collect statistics on collectable objects found and print
621 * debugging information. */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000622 for (gc = collectable.gc.gc_next; gc != &collectable;
Tim Peters9e4ca102001-10-11 18:31:31 +0000623 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000624 m++;
Jeremy Hylton06257772000-08-31 15:10:24 +0000625 if (debug & DEBUG_COLLECTABLE) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000626 debug_cycle("collectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000627 }
628 }
Tim Peters19b74c72002-07-01 03:52:19 +0000629 /* Call tp_clear on objects in the collectable set. This will cause
Tim Petersbf384c22003-04-06 00:11:39 +0000630 * the reference cycles to be broken. It may also cause some objects
631 * in finalizers and/or reachable_from_finalizers to be freed */
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000632 delete_garbage(&collectable, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000633
634 /* Collect statistics on uncollectable objects found and print
635 * debugging information. */
Tim Peters50c61d52003-04-06 01:50:50 +0000636 for (gc = finalizers.gc.gc_next;
Tim Petersbf384c22003-04-06 00:11:39 +0000637 gc != &finalizers;
638 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000639 n++;
Tim Petersbf384c22003-04-06 00:11:39 +0000640 if (debug & DEBUG_UNCOLLECTABLE)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000641 debug_cycle("uncollectable", FROM_GC(gc));
Tim Petersbf384c22003-04-06 00:11:39 +0000642 }
643 for (gc = reachable_from_finalizers.gc.gc_next;
644 gc != &reachable_from_finalizers;
645 gc = gc->gc.gc_next) {
646 n++;
647 if (debug & DEBUG_UNCOLLECTABLE)
648 debug_cycle("uncollectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000649 }
Jeremy Hylton06257772000-08-31 15:10:24 +0000650 if (debug & DEBUG_STATS) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000651 if (m == 0 && n == 0) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000652 PySys_WriteStderr("gc: done.\n");
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000653 }
654 else {
Jeremy Hylton06257772000-08-31 15:10:24 +0000655 PySys_WriteStderr(
656 "gc: done, %ld unreachable, %ld uncollectable.\n",
657 n+m, n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000658 }
659 }
660
661 /* Append instances in the uncollectable set to a Python
662 * reachable list of garbage. The programmer has to deal with
Tim Petersbf384c22003-04-06 00:11:39 +0000663 * this if they insist on creating this type of structure.
664 */
665 handle_finalizers(&finalizers, old, 1);
666 handle_finalizers(&reachable_from_finalizers, old, 0);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000667
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000668 if (PyErr_Occurred()) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000669 if (gc_str == NULL) {
670 gc_str = PyString_FromString("garbage collection");
671 }
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000672 PyErr_WriteUnraisable(gc_str);
673 Py_FatalError("unexpected exception during garbage collection");
674 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000675 return n+m;
676}
677
678static long
679collect_generations(void)
680{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000681 int i;
Vladimir Marangozovb16714b2000-07-10 05:37:39 +0000682 long n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000683
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000684 /* Find the oldest generation (higest numbered) where the count
685 * exceeds the threshold. Objects in the that generation and
686 * generations younger than it will be collected. */
687 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
688 if (generations[i].count > generations[i].threshold) {
689 n = collect(i);
690 break;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000691 }
692 }
693 return n;
694}
695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000696PyDoc_STRVAR(gc_enable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000697"enable() -> None\n"
698"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000699"Enable automatic garbage collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000700
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000701static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000702gc_enable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000703{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000704 enabled = 1;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000705 Py_INCREF(Py_None);
706 return Py_None;
707}
708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000709PyDoc_STRVAR(gc_disable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000710"disable() -> None\n"
711"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000712"Disable automatic garbage collection.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000713
714static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000715gc_disable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000716{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000717 enabled = 0;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000718 Py_INCREF(Py_None);
719 return Py_None;
720}
721
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000722PyDoc_STRVAR(gc_isenabled__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000723"isenabled() -> status\n"
724"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000725"Returns true if automatic garbage collection is enabled.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000726
727static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000728gc_isenabled(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000729{
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000730 return Py_BuildValue("i", enabled);
731}
732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000733PyDoc_STRVAR(gc_collect__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000734"collect() -> n\n"
735"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000736"Run a full collection. The number of unreachable objects is returned.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000737
738static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000739gc_collect(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000740{
741 long n;
742
Tim Peters50c61d52003-04-06 01:50:50 +0000743 if (collecting)
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000744 n = 0; /* already collecting, don't do anything */
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000745 else {
746 collecting = 1;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000747 n = collect(NUM_GENERATIONS - 1);
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000748 collecting = 0;
749 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000750
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000751 return Py_BuildValue("l", n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000752}
753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000754PyDoc_STRVAR(gc_set_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000755"set_debug(flags) -> None\n"
756"\n"
757"Set the garbage collection debugging flags. Debugging information is\n"
758"written to sys.stderr.\n"
759"\n"
760"flags is an integer and can have the following bits turned on:\n"
761"\n"
762" DEBUG_STATS - Print statistics during collection.\n"
763" DEBUG_COLLECTABLE - Print collectable objects found.\n"
764" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
765" DEBUG_INSTANCES - Print instance objects.\n"
766" DEBUG_OBJECTS - Print objects other than instances.\n"
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000767" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000768" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000769
770static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000771gc_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000772{
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000773 if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000774 return NULL;
775
776 Py_INCREF(Py_None);
777 return Py_None;
778}
779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000780PyDoc_STRVAR(gc_get_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000781"get_debug() -> flags\n"
782"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000783"Get the garbage collection debugging flags.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000784
785static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000786gc_get_debug(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000787{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000788 return Py_BuildValue("i", debug);
789}
790
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000791PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +0000792"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000793"\n"
794"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000795"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000796
797static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000798gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000799{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000800 int i;
801 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
802 &generations[0].threshold,
803 &generations[1].threshold,
804 &generations[2].threshold))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000805 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000806 for (i = 2; i < NUM_GENERATIONS; i++) {
807 /* generations higher than 2 get the same threshold */
808 generations[i].threshold = generations[2].threshold;
809 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000810
811 Py_INCREF(Py_None);
812 return Py_None;
813}
814
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000815PyDoc_STRVAR(gc_get_thresh__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000816"get_threshold() -> (threshold0, threshold1, threshold2)\n"
817"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000818"Return the current collection thresholds\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000819
820static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000821gc_get_thresh(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000822{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000823 return Py_BuildValue("(iii)",
824 generations[0].threshold,
825 generations[1].threshold,
826 generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000827}
828
Neil Schemenauer48c70342001-08-09 15:38:31 +0000829static int
Martin v. Löwis560da622001-11-24 09:24:51 +0000830referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000831{
Martin v. Löwisc8fe77b2001-11-29 18:08:31 +0000832 int i;
833 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
834 if (PyTuple_GET_ITEM(objs, i) == obj)
835 return 1;
Neil Schemenauer48c70342001-08-09 15:38:31 +0000836 return 0;
837}
838
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000839static int
Martin v. Löwis560da622001-11-24 09:24:51 +0000840gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000841{
842 PyGC_Head *gc;
843 PyObject *obj;
844 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000845 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000846 obj = FROM_GC(gc);
Neil Schemenauer48c70342001-08-09 15:38:31 +0000847 traverse = obj->ob_type->tp_traverse;
848 if (obj == objs || obj == resultlist)
849 continue;
Martin v. Löwis560da622001-11-24 09:24:51 +0000850 if (traverse(obj, (visitproc)referrersvisit, objs)) {
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000851 if (PyList_Append(resultlist, obj) < 0)
852 return 0; /* error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000853 }
854 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000855 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000856}
857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000858PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +0000859"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000860Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +0000861
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000862static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +0000863gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000864{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000865 int i;
Neil Schemenauer48c70342001-08-09 15:38:31 +0000866 PyObject *result = PyList_New(0);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000867 for (i = 0; i < NUM_GENERATIONS; i++) {
868 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
869 Py_DECREF(result);
870 return NULL;
871 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000872 }
Neil Schemenauer48c70342001-08-09 15:38:31 +0000873 return result;
874}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000875
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000876static int
877referrentsvisit(PyObject *obj, PyObject *list)
878{
879 if (PyList_Append(list, obj) < 0)
880 return 1;
881 return 0;
882}
883
884PyDoc_STRVAR(gc_get_referrents__doc__,
885"get_referrents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +0000886Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000887
888static PyObject *
889gc_get_referrents(PyObject *self, PyObject *args)
890{
891 int i;
892 PyObject *result = PyList_New(0);
893 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
Tim Peters93ad66d2003-04-05 17:15:44 +0000894 PyObject *obj = PyTuple_GET_ITEM(args, i);
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000895 traverseproc traverse = obj->ob_type->tp_traverse;
896 if (!traverse)
897 continue;
898 if (traverse(obj, (visitproc)referrentsvisit, result))
899 return NULL;
900 }
901 return result;
902}
903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000904PyDoc_STRVAR(gc_get_objects__doc__,
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000905"get_objects() -> [...]\n"
906"\n"
907"Return a list of objects tracked by the collector (excluding the list\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000908"returned).\n");
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000909
910/* appending objects in a GC list to a Python list */
Martin v. Löwis155aad12001-12-02 12:21:34 +0000911static int
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000912append_objects(PyObject *py_list, PyGC_Head *gc_list)
913{
914 PyGC_Head *gc;
Tim Peters9e4ca102001-10-11 18:31:31 +0000915 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000916 PyObject *op = FROM_GC(gc);
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000917 if (op != py_list) {
Martin v. Löwis155aad12001-12-02 12:21:34 +0000918 if (PyList_Append(py_list, op)) {
919 return -1; /* exception */
920 }
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000921 }
922 }
Martin v. Löwis155aad12001-12-02 12:21:34 +0000923 return 0;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000924}
925
926static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +0000927gc_get_objects(PyObject *self, PyObject *noargs)
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000928{
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000929 int i;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000930 PyObject* result;
931
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000932 result = PyList_New(0);
Tim Peters50c61d52003-04-06 01:50:50 +0000933 if (result == NULL)
Martin v. Löwisf8a6f242001-12-02 18:31:02 +0000934 return NULL;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000935 for (i = 0; i < NUM_GENERATIONS; i++) {
936 if (append_objects(result, GEN_HEAD(i))) {
937 Py_DECREF(result);
938 return NULL;
939 }
Martin v. Löwis155aad12001-12-02 12:21:34 +0000940 }
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000941 return result;
942}
943
944
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000945PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000946"This module provides access to the garbage collector for reference cycles.\n"
947"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000948"enable() -- Enable automatic garbage collection.\n"
949"disable() -- Disable automatic garbage collection.\n"
950"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000951"collect() -- Do a full collection right now.\n"
952"set_debug() -- Set debugging flags.\n"
953"get_debug() -- Get debugging flags.\n"
954"set_threshold() -- Set the collection thresholds.\n"
955"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000956"get_objects() -- Return a list of all objects tracked by the collector.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000957"get_referrers() -- Return the list of objects that refer to an object.\n"
958"get_referrents() -- Return the list of objects that an object refers to.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000959
960static PyMethodDef GcMethods[] = {
Tim Peters50c61d52003-04-06 01:50:50 +0000961 {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
962 {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
963 {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000964 {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +0000965 {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000966 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Tim Peters50c61d52003-04-06 01:50:50 +0000967 {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
968 {"collect", gc_collect, METH_NOARGS, gc_collect__doc__},
969 {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
Martin v. Löwis560da622001-11-24 09:24:51 +0000970 {"get_referrers", gc_get_referrers, METH_VARARGS,
971 gc_get_referrers__doc__},
Jeremy Hylton5bd378b2003-04-03 16:28:38 +0000972 {"get_referrents", gc_get_referrents, METH_VARARGS,
973 gc_get_referrents__doc__},
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000974 {NULL, NULL} /* Sentinel */
975};
976
977void
978initgc(void)
979{
980 PyObject *m;
981 PyObject *d;
982
983 m = Py_InitModule4("gc",
984 GcMethods,
985 gc__doc__,
986 NULL,
987 PYTHON_API_VERSION);
988 d = PyModule_GetDict(m);
989 if (garbage == NULL) {
990 garbage = PyList_New(0);
991 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000992 PyDict_SetItemString(d, "garbage", garbage);
993 PyDict_SetItemString(d, "DEBUG_STATS",
994 PyInt_FromLong(DEBUG_STATS));
995 PyDict_SetItemString(d, "DEBUG_COLLECTABLE",
996 PyInt_FromLong(DEBUG_COLLECTABLE));
997 PyDict_SetItemString(d, "DEBUG_UNCOLLECTABLE",
998 PyInt_FromLong(DEBUG_UNCOLLECTABLE));
999 PyDict_SetItemString(d, "DEBUG_INSTANCES",
1000 PyInt_FromLong(DEBUG_INSTANCES));
1001 PyDict_SetItemString(d, "DEBUG_OBJECTS",
1002 PyInt_FromLong(DEBUG_OBJECTS));
Neil Schemenauer544de1e2000-09-22 15:22:38 +00001003 PyDict_SetItemString(d, "DEBUG_SAVEALL",
1004 PyInt_FromLong(DEBUG_SAVEALL));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001005 PyDict_SetItemString(d, "DEBUG_LEAK",
1006 PyInt_FromLong(DEBUG_LEAK));
1007}
1008
Neil Schemenauer43411b52001-08-30 00:05:51 +00001009/* for debugging */
1010void _PyGC_Dump(PyGC_Head *g)
1011{
1012 _PyObject_Dump(FROM_GC(g));
1013}
1014
Neil Schemenauer43411b52001-08-30 00:05:51 +00001015/* extension modules might be compiled with GC support so these
1016 functions must always be available */
1017
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001018#undef PyObject_GC_Track
1019#undef PyObject_GC_UnTrack
1020#undef PyObject_GC_Del
1021#undef _PyObject_GC_Malloc
1022
Neil Schemenauer43411b52001-08-30 00:05:51 +00001023void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001024PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001025{
1026 _PyObject_GC_TRACK(op);
1027}
1028
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001029/* for binary compatibility with 2.2 */
Neil Schemenauer43411b52001-08-30 00:05:51 +00001030void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001031_PyObject_GC_Track(PyObject *op)
1032{
1033 PyObject_GC_Track(op);
1034}
1035
1036void
1037PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001038{
Tim Peters803526b2002-07-07 05:13:56 +00001039 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1040 * call PyObject_GC_UnTrack twice on an object.
1041 */
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001042 if (IS_TRACKED(op))
Guido van Rossumff413af2002-03-28 20:34:59 +00001043 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001044}
1045
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001046/* for binary compatibility with 2.2 */
1047void
1048_PyObject_GC_UnTrack(PyObject *op)
1049{
1050 PyObject_GC_UnTrack(op);
1051}
1052
Neil Schemenauer43411b52001-08-30 00:05:51 +00001053PyObject *
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001054_PyObject_GC_Malloc(size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001055{
1056 PyObject *op;
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001057 PyGC_Head *g = PyObject_MALLOC(sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001058 if (g == NULL)
Jeremy Hylton8a135182002-06-06 23:23:55 +00001059 return PyErr_NoMemory();
Tim Petersea405632002-07-02 00:52:30 +00001060 g->gc.gc_refs = GC_UNTRACKED;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001061 generations[0].count++; /* number of allocated GC objects */
1062 if (generations[0].count > generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001063 enabled &&
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001064 generations[0].threshold &&
Neil Schemenauer43411b52001-08-30 00:05:51 +00001065 !collecting &&
1066 !PyErr_Occurred()) {
1067 collecting = 1;
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001068 collect_generations();
Neil Schemenauer43411b52001-08-30 00:05:51 +00001069 collecting = 0;
1070 }
1071 op = FROM_GC(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001072 return op;
1073}
1074
1075PyObject *
1076_PyObject_GC_New(PyTypeObject *tp)
1077{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001078 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
Tim Petersfa8efab2002-04-28 01:57:25 +00001079 if (op != NULL)
1080 op = PyObject_INIT(op, tp);
1081 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001082}
1083
1084PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +00001085_PyObject_GC_NewVar(PyTypeObject *tp, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001086{
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001087 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
1088 PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
Tim Petersfa8efab2002-04-28 01:57:25 +00001089 if (op != NULL)
1090 op = PyObject_INIT_VAR(op, tp, nitems);
1091 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001092}
1093
1094PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +00001095_PyObject_GC_Resize(PyVarObject *op, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001096{
Tim Petersf2a67da2001-10-07 03:54:51 +00001097 const size_t basicsize = _PyObject_VAR_SIZE(op->ob_type, nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001098 PyGC_Head *g = AS_GC(op);
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001099 g = PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001100 if (g == NULL)
1101 return (PyVarObject *)PyErr_NoMemory();
1102 op = (PyVarObject *) FROM_GC(g);
Tim Peters6d483d32001-10-06 21:27:34 +00001103 op->ob_size = nitems;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001104 return op;
1105}
1106
1107void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001108PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001109{
Neil Schemenauer43411b52001-08-30 00:05:51 +00001110 PyGC_Head *g = AS_GC(op);
Neil Schemenauera2b11ec2002-05-21 15:53:24 +00001111 if (IS_TRACKED(op))
Neil Schemenauer43411b52001-08-30 00:05:51 +00001112 gc_list_remove(g);
Neil Schemenauer2880ae52002-05-04 05:35:20 +00001113 if (generations[0].count > 0) {
1114 generations[0].count--;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001115 }
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001116 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001117}
1118
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001119/* for binary compatibility with 2.2 */
1120#undef _PyObject_GC_Del
1121void
1122_PyObject_GC_Del(PyObject *op)
1123{
1124 PyObject_GC_Del(op);
1125}