blob: a0522a095242bf13bb9b85f0f66a8214f938024e [file] [log] [blame]
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001/*
2
3 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
23#ifdef WITH_CYCLE_GC
24
Neil Schemenauer43411b52001-08-30 00:05:51 +000025/* Get an object's GC head */
26#define AS_GC(o) ((PyGC_Head *)(o)-1)
27
28/* Get the object given the GC head */
29#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
30
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000031
32/*** Global GC state ***/
33
34/* linked lists of container objects */
Guido van Rossumbca8c2e2001-10-12 20:52:48 +000035PyGC_Head _PyGC_generation0 = {{&_PyGC_generation0, &_PyGC_generation0, 0}};
36static PyGC_Head generation1 = {{&generation1, &generation1, 0}};
37static PyGC_Head generation2 = {{&generation2, &generation2, 0}};
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000038static int generation = 0; /* current generation being collected */
39
40/* collection frequencies, XXX tune these */
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +000041static int enabled = 1; /* automatic collection enabled? */
Jeremy Hylton3263dc2b2000-09-05 15:44:50 +000042static int threshold0 = 700; /* net new containers before collection */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000043static int threshold1 = 10; /* generation0 collections before collecting 1 */
44static int threshold2 = 10; /* generation1 collections before collecting 2 */
45
46/* net new objects allocated since last collection */
47static int allocated;
48
Neil Schemenauer43411b52001-08-30 00:05:51 +000049/* true if we are currently running the collector */
50static int collecting;
51
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000052/* set for debugging information */
53#define DEBUG_STATS (1<<0) /* print collection statistics */
54#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
55#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
56#define DEBUG_INSTANCES (1<<3) /* print instances */
57#define DEBUG_OBJECTS (1<<4) /* print other objects */
Neil Schemenauer544de1e2000-09-22 15:22:38 +000058#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000059#define DEBUG_LEAK DEBUG_COLLECTABLE | \
60 DEBUG_UNCOLLECTABLE | \
61 DEBUG_INSTANCES | \
Neil Schemenauer544de1e2000-09-22 15:22:38 +000062 DEBUG_OBJECTS | \
63 DEBUG_SAVEALL
Jeremy Hyltonb709df32000-09-01 02:47:25 +000064static int debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000065
Neil Schemenauer43411b52001-08-30 00:05:51 +000066/* Special gc_refs value */
67#define GC_MOVED -123
68
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000069/* list of uncollectable objects */
70static PyObject *garbage;
71
Jeremy Hyltonb709df32000-09-01 02:47:25 +000072/* Python string to use if unhandled exception occurs */
73static PyObject *gc_str;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000074
75/*** list functions ***/
76
77static void
78gc_list_init(PyGC_Head *list)
79{
Tim Peters9e4ca102001-10-11 18:31:31 +000080 list->gc.gc_prev = list;
81 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000082}
83
84static void
85gc_list_append(PyGC_Head *node, PyGC_Head *list)
86{
Tim Peters9e4ca102001-10-11 18:31:31 +000087 node->gc.gc_next = list;
88 node->gc.gc_prev = list->gc.gc_prev;
89 node->gc.gc_prev->gc.gc_next = node;
90 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000091}
92
93static void
94gc_list_remove(PyGC_Head *node)
95{
Tim Peters9e4ca102001-10-11 18:31:31 +000096 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
97 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
98 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000099}
100
101static void
102gc_list_move(PyGC_Head *from, PyGC_Head *to)
103{
Tim Peters9e4ca102001-10-11 18:31:31 +0000104 if (from->gc.gc_next == from) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000105 /* empty from list */
106 gc_list_init(to);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000107 }
108 else {
Tim Peters9e4ca102001-10-11 18:31:31 +0000109 to->gc.gc_next = from->gc.gc_next;
110 to->gc.gc_next->gc.gc_prev = to;
111 to->gc.gc_prev = from->gc.gc_prev;
112 to->gc.gc_prev->gc.gc_next = to;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000113 }
114 gc_list_init(from);
115}
116
117/* append a list onto another list, from becomes an empty list */
118static void
119gc_list_merge(PyGC_Head *from, PyGC_Head *to)
120{
121 PyGC_Head *tail;
Tim Peters9e4ca102001-10-11 18:31:31 +0000122 if (from->gc.gc_next != from) {
123 tail = to->gc.gc_prev;
124 tail->gc.gc_next = from->gc.gc_next;
125 tail->gc.gc_next->gc.gc_prev = tail;
126 to->gc.gc_prev = from->gc.gc_prev;
127 to->gc.gc_prev->gc.gc_next = to;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000128 }
129 gc_list_init(from);
130}
131
132static long
133gc_list_size(PyGC_Head *list)
134{
135 PyGC_Head *gc;
136 long n = 0;
Tim Peters9e4ca102001-10-11 18:31:31 +0000137 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000138 n++;
139 }
140 return n;
141}
142
143/*** end of list stuff ***/
144
145
Neil Schemenauer43411b52001-08-30 00:05:51 +0000146
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000147/* Set all gc_refs = ob_refcnt */
148static void
149update_refs(PyGC_Head *containers)
150{
Tim Peters9e4ca102001-10-11 18:31:31 +0000151 PyGC_Head *gc = containers->gc.gc_next;
152 for (; gc != containers; gc=gc->gc.gc_next) {
153 gc->gc.gc_refs = FROM_GC(gc)->ob_refcnt;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000154 }
155}
156
157static int
158visit_decref(PyObject *op, void *data)
159{
160 if (op && PyObject_IS_GC(op)) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000161 PyGC_Head *gc = AS_GC(op);
Tim Peters9e4ca102001-10-11 18:31:31 +0000162 if (gc->gc.gc_next != NULL)
163 AS_GC(op)->gc.gc_refs--;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000164 }
165 return 0;
166}
167
168/* Subtract internal references from gc_refs */
169static void
170subtract_refs(PyGC_Head *containers)
171{
172 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000173 PyGC_Head *gc = containers->gc.gc_next;
174 for (; gc != containers; gc=gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000175 traverse = FROM_GC(gc)->ob_type->tp_traverse;
176 (void) traverse(FROM_GC(gc),
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000177 (visitproc)visit_decref,
178 NULL);
179 }
180}
181
182/* Append objects with gc_refs > 0 to roots list */
183static void
184move_roots(PyGC_Head *containers, PyGC_Head *roots)
185{
186 PyGC_Head *next;
Tim Peters9e4ca102001-10-11 18:31:31 +0000187 PyGC_Head *gc = containers->gc.gc_next;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000188 while (gc != containers) {
Tim Peters9e4ca102001-10-11 18:31:31 +0000189 next = gc->gc.gc_next;
190 if (gc->gc.gc_refs > 0) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000191 gc_list_remove(gc);
192 gc_list_append(gc, roots);
Tim Peters9e4ca102001-10-11 18:31:31 +0000193 gc->gc.gc_refs = GC_MOVED;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000194 }
195 gc = next;
196 }
197}
198
199static int
Neil Schemenauer43411b52001-08-30 00:05:51 +0000200visit_move(PyObject *op, PyGC_Head *tolist)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000201{
202 if (PyObject_IS_GC(op)) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000203 PyGC_Head *gc = AS_GC(op);
Tim Peters9e4ca102001-10-11 18:31:31 +0000204 if (gc->gc.gc_next != NULL && gc->gc.gc_refs != GC_MOVED) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000205 gc_list_remove(gc);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000206 gc_list_append(gc, tolist);
Tim Peters9e4ca102001-10-11 18:31:31 +0000207 gc->gc.gc_refs = GC_MOVED;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000208 }
209 }
210 return 0;
211}
212
213/* Move objects referenced from reachable to reachable set. */
214static void
215move_root_reachable(PyGC_Head *reachable)
216{
217 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000218 PyGC_Head *gc = reachable->gc.gc_next;
219 for (; gc != reachable; gc=gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000220 /* careful, reachable list is growing here */
Neil Schemenauer43411b52001-08-30 00:05:51 +0000221 PyObject *op = FROM_GC(gc);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000222 traverse = op->ob_type->tp_traverse;
223 (void) traverse(op,
Neil Schemenauer43411b52001-08-30 00:05:51 +0000224 (visitproc)visit_move,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000225 (void *)reachable);
226 }
227}
228
Neil Schemenauer43411b52001-08-30 00:05:51 +0000229/* Move all objects with finalizers (instances with __del__) */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000230static void
231move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
232{
233 PyGC_Head *next;
Tim Peters9e4ca102001-10-11 18:31:31 +0000234 PyGC_Head *gc = unreachable->gc.gc_next;
Jeremy Hylton06257772000-08-31 15:10:24 +0000235 static PyObject *delstr = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000236 if (delstr == NULL) {
237 delstr = PyString_InternFromString("__del__");
Jeremy Hylton06257772000-08-31 15:10:24 +0000238 if (delstr == NULL)
239 Py_FatalError("PyGC: can't initialize __del__ string");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000240 }
241 for (; gc != unreachable; gc=next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000242 PyObject *op = FROM_GC(gc);
Tim Peters9e4ca102001-10-11 18:31:31 +0000243 next = gc->gc.gc_next;
Guido van Rossum8cc705e2001-11-01 14:23:28 +0000244 if ((PyInstance_Check(op) ||
245 PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE)) &&
246 PyObject_HasAttr(op, delstr)) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000247 gc_list_remove(gc);
248 gc_list_append(gc, finalizers);
249 }
250 }
251}
252
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000253/* Move objects referenced from roots to roots */
254static void
255move_finalizer_reachable(PyGC_Head *finalizers)
256{
257 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000258 PyGC_Head *gc = finalizers->gc.gc_next;
259 for (; gc != finalizers; gc=gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000260 /* careful, finalizers list is growing here */
Neil Schemenauer43411b52001-08-30 00:05:51 +0000261 traverse = FROM_GC(gc)->ob_type->tp_traverse;
262 (void) traverse(FROM_GC(gc),
263 (visitproc)visit_move,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000264 (void *)finalizers);
265 }
266}
267
268static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000269debug_instance(char *msg, PyInstanceObject *inst)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000270{
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000271 char *cname;
272 /* be careful not to create new dictionaries */
273 PyObject *classname = inst->in_class->cl_name;
274 if (classname != NULL && PyString_Check(classname))
275 cname = PyString_AsString(classname);
276 else
277 cname = "?";
Jeremy Hylton06257772000-08-31 15:10:24 +0000278 PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
279 msg, cname, inst);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000280}
281
282static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000283debug_cycle(char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000284{
285 if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000286 debug_instance(msg, (PyInstanceObject *)op);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000287 }
288 else if (debug & DEBUG_OBJECTS) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000289 PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
290 msg, op->ob_type->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000291 }
292}
293
294/* Handle uncollectable garbage (cycles with finalizers). */
295static void
296handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
297{
298 PyGC_Head *gc;
299 if (garbage == NULL) {
300 garbage = PyList_New(0);
301 }
Tim Peters9e4ca102001-10-11 18:31:31 +0000302 for (gc = finalizers->gc.gc_next; gc != finalizers;
303 gc = finalizers->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000304 PyObject *op = FROM_GC(gc);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000305 if ((debug & DEBUG_SAVEALL) || PyInstance_Check(op)) {
306 /* If SAVEALL is not set then just append
307 * instances to the list of garbage. We assume
308 * that all objects in the finalizers list are
309 * reachable from instances. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000310 PyList_Append(garbage, op);
311 }
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000312 /* object is now reachable again */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000313 gc_list_remove(gc);
314 gc_list_append(gc, old);
315 }
316}
317
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000318/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000319 * tricky business as the lists can be changing and we don't know which
320 * objects may be freed. It is possible I screwed something up here. */
321static void
322delete_garbage(PyGC_Head *unreachable, PyGC_Head *old)
323{
324 inquiry clear;
325
Tim Peters9e4ca102001-10-11 18:31:31 +0000326 while (unreachable->gc.gc_next != unreachable) {
327 PyGC_Head *gc = unreachable->gc.gc_next;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000328 PyObject *op = FROM_GC(gc);
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000329 if (debug & DEBUG_SAVEALL) {
330 PyList_Append(garbage, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000331 }
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000332 else {
333 if ((clear = op->ob_type->tp_clear) != NULL) {
334 Py_INCREF(op);
335 clear((PyObject *)op);
336 Py_DECREF(op);
337 }
338 }
Tim Peters9e4ca102001-10-11 18:31:31 +0000339 if (unreachable->gc.gc_next == gc) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000340 /* object is still alive, move it, it may die later */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000341 gc_list_remove(gc);
342 gc_list_append(gc, old);
343 }
344 }
345}
346
347/* This is the main function. Read this to understand how the
348 * collection process works. */
349static long
350collect(PyGC_Head *young, PyGC_Head *old)
351{
352 long n = 0;
353 long m = 0;
354 PyGC_Head reachable;
355 PyGC_Head unreachable;
356 PyGC_Head finalizers;
357 PyGC_Head *gc;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000358
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000359 if (debug & DEBUG_STATS) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000360 PySys_WriteStderr(
361 "gc: collecting generation %d...\n"
362 "gc: objects in each generation: %ld %ld %ld\n",
363 generation,
Neil Schemenauer43411b52001-08-30 00:05:51 +0000364 gc_list_size(&_PyGC_generation0),
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000365 gc_list_size(&generation1),
366 gc_list_size(&generation2));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000367 }
368
369 /* Using ob_refcnt and gc_refs, calculate which objects in the
370 * container set are reachable from outside the set (ie. have a
371 * refcount greater than 0 when all the references within the
372 * set are taken into account */
373 update_refs(young);
374 subtract_refs(young);
375
376 /* Move everything reachable from outside the set into the
377 * reachable set (ie. gc_refs > 0). Next, move everything
378 * reachable from objects in the reachable set. */
379 gc_list_init(&reachable);
380 move_roots(young, &reachable);
381 move_root_reachable(&reachable);
382
383 /* move unreachable objects to a temporary list, new objects can be
384 * allocated after this point */
385 gc_list_init(&unreachable);
386 gc_list_move(young, &unreachable);
387
388 /* move reachable objects to next generation */
389 gc_list_merge(&reachable, old);
390
391 /* Move objects reachable from finalizers, we can't safely delete
392 * them. Python programmers should take care not to create such
393 * things. For Python finalizers means instance objects with
394 * __del__ methods. */
395 gc_list_init(&finalizers);
396 move_finalizers(&unreachable, &finalizers);
397 move_finalizer_reachable(&finalizers);
398
399 /* Collect statistics on collectable objects found and print
400 * debugging information. */
Tim Peters9e4ca102001-10-11 18:31:31 +0000401 for (gc = unreachable.gc.gc_next; gc != &unreachable;
402 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000403 m++;
Jeremy Hylton06257772000-08-31 15:10:24 +0000404 if (debug & DEBUG_COLLECTABLE) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000405 debug_cycle("collectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000406 }
407 }
408 /* call tp_clear on objects in the collectable set. This will cause
409 * the reference cycles to be broken. It may also cause some objects in
410 * finalizers to be freed */
411 delete_garbage(&unreachable, old);
412
413 /* Collect statistics on uncollectable objects found and print
414 * debugging information. */
Tim Peters9e4ca102001-10-11 18:31:31 +0000415 for (gc = finalizers.gc.gc_next; gc != &finalizers;
416 gc = gc->gc.gc_next) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000417 n++;
Jeremy Hylton06257772000-08-31 15:10:24 +0000418 if (debug & DEBUG_UNCOLLECTABLE) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000419 debug_cycle("uncollectable", FROM_GC(gc));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000420 }
421 }
Jeremy Hylton06257772000-08-31 15:10:24 +0000422 if (debug & DEBUG_STATS) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000423 if (m == 0 && n == 0) {
Jeremy Hylton06257772000-08-31 15:10:24 +0000424 PySys_WriteStderr("gc: done.\n");
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000425 }
426 else {
Jeremy Hylton06257772000-08-31 15:10:24 +0000427 PySys_WriteStderr(
428 "gc: done, %ld unreachable, %ld uncollectable.\n",
429 n+m, n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000430 }
431 }
432
433 /* Append instances in the uncollectable set to a Python
434 * reachable list of garbage. The programmer has to deal with
435 * this if they insist on creating this type of structure. */
436 handle_finalizers(&finalizers, old);
437
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000438 if (PyErr_Occurred()) {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000439 if (gc_str == NULL) {
440 gc_str = PyString_FromString("garbage collection");
441 }
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000442 PyErr_WriteUnraisable(gc_str);
443 Py_FatalError("unexpected exception during garbage collection");
444 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000445 allocated = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000446 return n+m;
447}
448
449static long
450collect_generations(void)
451{
452 static long collections0 = 0;
453 static long collections1 = 0;
Vladimir Marangozovb16714b2000-07-10 05:37:39 +0000454 long n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000455
456
457 if (collections1 > threshold2) {
458 generation = 2;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000459 gc_list_merge(&_PyGC_generation0, &generation2);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000460 gc_list_merge(&generation1, &generation2);
Tim Peters9e4ca102001-10-11 18:31:31 +0000461 if (generation2.gc.gc_next != &generation2) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000462 n = collect(&generation2, &generation2);
463 }
464 collections1 = 0;
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000465 }
466 else if (collections0 > threshold1) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000467 generation = 1;
468 collections1++;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000469 gc_list_merge(&_PyGC_generation0, &generation1);
Tim Peters9e4ca102001-10-11 18:31:31 +0000470 if (generation1.gc.gc_next != &generation1) {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000471 n = collect(&generation1, &generation2);
472 }
473 collections0 = 0;
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000474 }
475 else {
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000476 generation = 0;
477 collections0++;
Tim Peters9e4ca102001-10-11 18:31:31 +0000478 if (_PyGC_generation0.gc.gc_next != &_PyGC_generation0) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000479 n = collect(&_PyGC_generation0, &generation1);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000480 }
481 }
482 return n;
483}
484
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000485static char gc_enable__doc__[] =
486"enable() -> None\n"
487"\n"
488"Enable automatic garbage collection.\n"
489;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000490
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000491static PyObject *
492gc_enable(PyObject *self, PyObject *args)
493{
494
495 if (!PyArg_ParseTuple(args, ":enable")) /* check no args */
496 return NULL;
497
498 enabled = 1;
499
500 Py_INCREF(Py_None);
501 return Py_None;
502}
503
504static char gc_disable__doc__[] =
505"disable() -> None\n"
506"\n"
507"Disable automatic garbage collection.\n"
508;
509
510static PyObject *
511gc_disable(PyObject *self, PyObject *args)
512{
513
514 if (!PyArg_ParseTuple(args, ":disable")) /* check no args */
515 return NULL;
516
517 enabled = 0;
518
519 Py_INCREF(Py_None);
520 return Py_None;
521}
522
523static char gc_isenabled__doc__[] =
524"isenabled() -> status\n"
525"\n"
526"Returns true if automatic garbage collection is enabled.\n"
527;
528
529static PyObject *
530gc_isenabled(PyObject *self, PyObject *args)
531{
532
533 if (!PyArg_ParseTuple(args, ":isenabled")) /* check no args */
534 return NULL;
535
536 return Py_BuildValue("i", enabled);
537}
538
539static char gc_collect__doc__[] =
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000540"collect() -> n\n"
541"\n"
542"Run a full collection. The number of unreachable objects is returned.\n"
543;
544
545static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000546gc_collect(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000547{
548 long n;
549
Fred Drakecc1be242000-07-12 04:42:23 +0000550 if (!PyArg_ParseTuple(args, ":collect")) /* check no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000551 return NULL;
552
Neil Schemenauere8c40cb2001-10-31 23:09:35 +0000553 if (collecting) {
554 n = 0; /* already collecting, don't do anything */
555 }
556 else {
557 collecting = 1;
558 generation = 2;
559 gc_list_merge(&_PyGC_generation0, &generation2);
560 gc_list_merge(&generation1, &generation2);
561 n = collect(&generation2, &generation2);
562 collecting = 0;
563 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000564
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000565 return Py_BuildValue("l", n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000566}
567
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000568static char gc_set_debug__doc__[] =
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000569"set_debug(flags) -> None\n"
570"\n"
571"Set the garbage collection debugging flags. Debugging information is\n"
572"written to sys.stderr.\n"
573"\n"
574"flags is an integer and can have the following bits turned on:\n"
575"\n"
576" DEBUG_STATS - Print statistics during collection.\n"
577" DEBUG_COLLECTABLE - Print collectable objects found.\n"
578" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
579" DEBUG_INSTANCES - Print instance objects.\n"
580" DEBUG_OBJECTS - Print objects other than instances.\n"
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000581" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000582" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n"
583;
584
585static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000586gc_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000587{
Neil Schemenauer7760cff2000-09-22 22:35:36 +0000588 if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000589 return NULL;
590
591 Py_INCREF(Py_None);
592 return Py_None;
593}
594
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000595static char gc_get_debug__doc__[] =
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000596"get_debug() -> flags\n"
597"\n"
598"Get the garbage collection debugging flags.\n"
599;
600
601static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000602gc_get_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000603{
Fred Drakecc1be242000-07-12 04:42:23 +0000604 if (!PyArg_ParseTuple(args, ":get_debug")) /* no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000605 return NULL;
606
607 return Py_BuildValue("i", debug);
608}
609
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000610static char gc_set_thresh__doc__[] =
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000611"set_threshold(threshold0, [threhold1, threshold2]) -> None\n"
612"\n"
613"Sets the collection thresholds. Setting threshold0 to zero disables\n"
614"collection.\n"
615;
616
617static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000618gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000619{
Fred Drakecc1be242000-07-12 04:42:23 +0000620 if (!PyArg_ParseTuple(args, "i|ii:set_threshold", &threshold0,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000621 &threshold1, &threshold2))
622 return NULL;
623
624 Py_INCREF(Py_None);
625 return Py_None;
626}
627
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000628static char gc_get_thresh__doc__[] =
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000629"get_threshold() -> (threshold0, threshold1, threshold2)\n"
630"\n"
631"Return the current collection thresholds\n"
632;
633
634static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000635gc_get_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000636{
Fred Drakecc1be242000-07-12 04:42:23 +0000637 if (!PyArg_ParseTuple(args, ":get_threshold")) /* no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000638 return NULL;
639
640 return Py_BuildValue("(iii)", threshold0, threshold1, threshold2);
641}
642
Neil Schemenauer48c70342001-08-09 15:38:31 +0000643static int
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000644referentsvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000645{
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000646 if (PySequence_Contains(objs, obj)) {
Neil Schemenauer48c70342001-08-09 15:38:31 +0000647 return 1;
648 }
649 return 0;
650}
651
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000652static int
Neil Schemenauer48c70342001-08-09 15:38:31 +0000653gc_referents_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
654{
655 PyGC_Head *gc;
656 PyObject *obj;
657 traverseproc traverse;
Tim Peters9e4ca102001-10-11 18:31:31 +0000658 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000659 obj = FROM_GC(gc);
Neil Schemenauer48c70342001-08-09 15:38:31 +0000660 traverse = obj->ob_type->tp_traverse;
661 if (obj == objs || obj == resultlist)
662 continue;
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000663 if (traverse(obj, (visitproc)referentsvisit, objs)) {
664 if (PyList_Append(resultlist, obj) < 0)
665 return 0; /* error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000666 }
667 }
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000668 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +0000669}
670
671static char gc_get_referents__doc__[]=
672"get_referents(*objs) -> list\n\
673Return the list of objects that directly refer to any of objs.";
674
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000675static PyObject *
676gc_get_referents(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +0000677{
678 PyObject *result = PyList_New(0);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000679 if (!(gc_referents_for(args, &_PyGC_generation0, result) &&
Neil Schemenauer17e7be62001-08-10 14:46:47 +0000680 gc_referents_for(args, &generation1, result) &&
681 gc_referents_for(args, &generation2, result))) {
682 Py_DECREF(result);
683 return NULL;
684 }
Neil Schemenauer48c70342001-08-09 15:38:31 +0000685 return result;
686}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000687
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000688static char gc_get_objects__doc__[] =
689"get_objects() -> [...]\n"
690"\n"
691"Return a list of objects tracked by the collector (excluding the list\n"
692"returned).\n"
693;
694
695/* appending objects in a GC list to a Python list */
696static void
697append_objects(PyObject *py_list, PyGC_Head *gc_list)
698{
699 PyGC_Head *gc;
Tim Peters9e4ca102001-10-11 18:31:31 +0000700 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
Neil Schemenauer43411b52001-08-30 00:05:51 +0000701 PyObject *op = FROM_GC(gc);
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000702 if (op != py_list) {
703 Py_INCREF(op);
704 PyList_Append(py_list, op);
705 }
706 }
707}
708
709static PyObject *
710gc_get_objects(PyObject *self, PyObject *args)
711{
712 PyObject* result;
713
714 if (!PyArg_ParseTuple(args, ":get_objects")) /* check no args */
715 return NULL;
716 result = PyList_New(0);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000717 append_objects(result, &_PyGC_generation0);
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000718 append_objects(result, &generation1);
719 append_objects(result, &generation2);
720 return result;
721}
722
723
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000724static char gc__doc__ [] =
725"This module provides access to the garbage collector for reference cycles.\n"
726"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000727"enable() -- Enable automatic garbage collection.\n"
728"disable() -- Disable automatic garbage collection.\n"
729"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000730"collect() -- Do a full collection right now.\n"
731"set_debug() -- Set debugging flags.\n"
732"get_debug() -- Get debugging flags.\n"
733"set_threshold() -- Set the collection thresholds.\n"
734"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000735"get_objects() -- Return a list of all objects tracked by the collector.\n"
Neil Schemenauer48c70342001-08-09 15:38:31 +0000736"get_referents() -- Return the list of objects that refer to an object.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000737;
738
739static PyMethodDef GcMethods[] = {
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000740 {"enable", gc_enable, METH_VARARGS, gc_enable__doc__},
741 {"disable", gc_disable, METH_VARARGS, gc_disable__doc__},
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +0000742 {"isenabled", gc_isenabled, METH_VARARGS, gc_isenabled__doc__},
743 {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
744 {"get_debug", gc_get_debug, METH_VARARGS, gc_get_debug__doc__},
745 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
746 {"get_threshold", gc_get_thresh, METH_VARARGS, gc_get_thresh__doc__},
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000747 {"collect", gc_collect, METH_VARARGS, gc_collect__doc__},
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +0000748 {"get_objects", gc_get_objects,METH_VARARGS, gc_get_objects__doc__},
Neil Schemenauer48c70342001-08-09 15:38:31 +0000749 {"get_referents", gc_get_referents, METH_VARARGS,
750 gc_get_referents__doc__},
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000751 {NULL, NULL} /* Sentinel */
752};
753
754void
755initgc(void)
756{
757 PyObject *m;
758 PyObject *d;
759
760 m = Py_InitModule4("gc",
761 GcMethods,
762 gc__doc__,
763 NULL,
764 PYTHON_API_VERSION);
765 d = PyModule_GetDict(m);
766 if (garbage == NULL) {
767 garbage = PyList_New(0);
768 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000769 PyDict_SetItemString(d, "garbage", garbage);
770 PyDict_SetItemString(d, "DEBUG_STATS",
771 PyInt_FromLong(DEBUG_STATS));
772 PyDict_SetItemString(d, "DEBUG_COLLECTABLE",
773 PyInt_FromLong(DEBUG_COLLECTABLE));
774 PyDict_SetItemString(d, "DEBUG_UNCOLLECTABLE",
775 PyInt_FromLong(DEBUG_UNCOLLECTABLE));
776 PyDict_SetItemString(d, "DEBUG_INSTANCES",
777 PyInt_FromLong(DEBUG_INSTANCES));
778 PyDict_SetItemString(d, "DEBUG_OBJECTS",
779 PyInt_FromLong(DEBUG_OBJECTS));
Neil Schemenauer544de1e2000-09-22 15:22:38 +0000780 PyDict_SetItemString(d, "DEBUG_SAVEALL",
781 PyInt_FromLong(DEBUG_SAVEALL));
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000782 PyDict_SetItemString(d, "DEBUG_LEAK",
783 PyInt_FromLong(DEBUG_LEAK));
784}
785
Neil Schemenauer43411b52001-08-30 00:05:51 +0000786/* for debugging */
787void _PyGC_Dump(PyGC_Head *g)
788{
789 _PyObject_Dump(FROM_GC(g));
790}
791
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000792#endif /* WITH_CYCLE_GC */
Neil Schemenauer43411b52001-08-30 00:05:51 +0000793
794/* extension modules might be compiled with GC support so these
795 functions must always be available */
796
797void
798_PyObject_GC_Track(PyObject *op)
799{
800 _PyObject_GC_TRACK(op);
801}
802
803void
804_PyObject_GC_UnTrack(PyObject *op)
805{
806 _PyObject_GC_UNTRACK(op);
807}
808
809PyObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000810_PyObject_GC_Malloc(PyTypeObject *tp, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000811{
812 PyObject *op;
Tim Petersf2a67da2001-10-07 03:54:51 +0000813 const size_t basicsize = _PyObject_VAR_SIZE(tp, nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000814#ifdef WITH_CYCLE_GC
Tim Petersf2a67da2001-10-07 03:54:51 +0000815 const size_t nbytes = sizeof(PyGC_Head) + basicsize;
816 PyGC_Head *g = PyObject_MALLOC(nbytes);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000817 if (g == NULL)
818 return (PyObject *)PyErr_NoMemory();
Tim Peters9e4ca102001-10-11 18:31:31 +0000819 g->gc.gc_next = NULL;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000820 allocated++;
821 if (allocated > threshold0 &&
822 enabled &&
823 threshold0 &&
824 !collecting &&
825 !PyErr_Occurred()) {
826 collecting = 1;
827 collect_generations();
828 collecting = 0;
829 }
830 op = FROM_GC(g);
831#else
Tim Peters6d483d32001-10-06 21:27:34 +0000832 op = PyObject_MALLOC(basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000833 if (op == NULL)
834 return (PyObject *)PyErr_NoMemory();
835
836#endif
837 return op;
838}
839
840PyObject *
841_PyObject_GC_New(PyTypeObject *tp)
842{
Tim Peters6d483d32001-10-06 21:27:34 +0000843 PyObject *op = _PyObject_GC_Malloc(tp, 0);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000844 return PyObject_INIT(op, tp);
845}
846
847PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000848_PyObject_GC_NewVar(PyTypeObject *tp, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000849{
Tim Peters6d483d32001-10-06 21:27:34 +0000850 PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(tp, nitems);
851 return PyObject_INIT_VAR(op, tp, nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000852}
853
854PyVarObject *
Tim Peters6d483d32001-10-06 21:27:34 +0000855_PyObject_GC_Resize(PyVarObject *op, int nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000856{
Tim Petersf2a67da2001-10-07 03:54:51 +0000857 const size_t basicsize = _PyObject_VAR_SIZE(op->ob_type, nitems);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000858#ifdef WITH_CYCLE_GC
859 PyGC_Head *g = AS_GC(op);
Tim Peters6d483d32001-10-06 21:27:34 +0000860 g = PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000861 if (g == NULL)
862 return (PyVarObject *)PyErr_NoMemory();
863 op = (PyVarObject *) FROM_GC(g);
864#else
Tim Peters6d483d32001-10-06 21:27:34 +0000865 op = PyObject_REALLOC(op, basicsize);
Neil Schemenauer43411b52001-08-30 00:05:51 +0000866 if (op == NULL)
867 return (PyVarObject *)PyErr_NoMemory();
868#endif
Tim Peters6d483d32001-10-06 21:27:34 +0000869 op->ob_size = nitems;
Neil Schemenauer43411b52001-08-30 00:05:51 +0000870 return op;
871}
872
873void
874_PyObject_GC_Del(PyObject *op)
875{
876#ifdef WITH_CYCLE_GC
877 PyGC_Head *g = AS_GC(op);
Tim Peters9e4ca102001-10-11 18:31:31 +0000878 if (g->gc.gc_next != NULL)
Neil Schemenauer43411b52001-08-30 00:05:51 +0000879 gc_list_remove(g);
880 if (allocated > 0) {
881 allocated--;
882 }
883 PyObject_FREE(g);
884#else
885 PyObject_FREE(op);
886#endif
887}
888