blob: 60b4fe7f14abf0e69206b9c69a18644925df563d [file] [log] [blame]
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001/*
2
3 Reference Cycle Garbage Collection
4 ==================================
5
6 Neil Schemenauer <nascheme@enme.ucalgary.ca>
7
8 Based on a post on the python-dev list. Ideas from Guido van Rossum,
9 Eric Tiedemann, and various others.
10
11 http://www.enme.calgary.ca/~nascheme/python/gc.html
12 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
19 TODO:
20 use a different interface for set_debug() (keywords)?
21 tune parameters
22
23*/
24
25
26#include "Python.h"
27
28#ifdef WITH_CYCLE_GC
29
30/* magic gc_refs value */
31#define GC_MOVED -1
32
33/*** Global GC state ***/
34
35/* linked lists of container objects */
36static PyGC_Head generation0 = {&generation0, &generation0, 0};
37static PyGC_Head generation1 = {&generation1, &generation1, 0};
38static PyGC_Head generation2 = {&generation2, &generation2, 0};
39static int generation = 0; /* current generation being collected */
40
41/* collection frequencies, XXX tune these */
42static int threshold0 = 100; /* net new containers before collection */
43static 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
49/* set for debugging information */
50#define DEBUG_STATS (1<<0) /* print collection statistics */
51#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
52#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
53#define DEBUG_INSTANCES (1<<3) /* print instances */
54#define DEBUG_OBJECTS (1<<4) /* print other objects */
55#define DEBUG_LEAK DEBUG_COLLECTABLE | \
56 DEBUG_UNCOLLECTABLE | \
57 DEBUG_INSTANCES | \
58 DEBUG_OBJECTS
59static int debug;
60
61/* list of uncollectable objects */
62static PyObject *garbage;
63
64
65/*** list functions ***/
66
67static void
68gc_list_init(PyGC_Head *list)
69{
70 list->gc_prev = list;
71 list->gc_next = list;
72}
73
74static void
75gc_list_append(PyGC_Head *node, PyGC_Head *list)
76{
77 node->gc_next = list;
78 node->gc_prev = list->gc_prev;
79 node->gc_prev->gc_next = node;
80 list->gc_prev = node;
81}
82
83static void
84gc_list_remove(PyGC_Head *node)
85{
86 node->gc_prev->gc_next = node->gc_next;
87 node->gc_next->gc_prev = node->gc_prev;
88#ifdef Py_DEBUG
89 node->gc_prev = NULL;
90 node->gc_next = NULL;
91#endif
92}
93
94static void
95gc_list_move(PyGC_Head *from, PyGC_Head *to)
96{
97 if (from->gc_next == from) {
98 /* empty from list */
99 gc_list_init(to);
100 } else {
101 to->gc_next = from->gc_next;
102 to->gc_next->gc_prev = to;
103 to->gc_prev = from->gc_prev;
104 to->gc_prev->gc_next = to;
105 }
106 gc_list_init(from);
107}
108
109/* append a list onto another list, from becomes an empty list */
110static void
111gc_list_merge(PyGC_Head *from, PyGC_Head *to)
112{
113 PyGC_Head *tail;
114 if (from->gc_next != from) {
115 tail = to->gc_prev;
116 tail->gc_next = from->gc_next;
117 tail->gc_next->gc_prev = tail;
118 to->gc_prev = from->gc_prev;
119 to->gc_prev->gc_next = to;
120 }
121 gc_list_init(from);
122}
123
124static long
125gc_list_size(PyGC_Head *list)
126{
127 PyGC_Head *gc;
128 long n = 0;
129 for (gc = list->gc_next; gc != list; gc = gc->gc_next) {
130 n++;
131 }
132 return n;
133}
134
135/*** end of list stuff ***/
136
137
138/* Set all gc_refs = ob_refcnt */
139static void
140update_refs(PyGC_Head *containers)
141{
142 PyGC_Head *gc = containers->gc_next;
143 for (; gc != containers; gc=gc->gc_next) {
144 gc->gc_refs = PyObject_FROM_GC(gc)->ob_refcnt;
145 }
146}
147
148static int
149visit_decref(PyObject *op, void *data)
150{
151 if (op && PyObject_IS_GC(op)) {
152 PyObject_AS_GC(op)->gc_refs--;
153 }
154 return 0;
155}
156
157/* Subtract internal references from gc_refs */
158static void
159subtract_refs(PyGC_Head *containers)
160{
161 traverseproc traverse;
162 PyGC_Head *gc = containers->gc_next;
163 for (; gc != containers; gc=gc->gc_next) {
164 traverse = PyObject_FROM_GC(gc)->ob_type->tp_traverse;
165 (void) traverse(PyObject_FROM_GC(gc),
166 (visitproc)visit_decref,
167 NULL);
168 }
169}
170
171/* Append objects with gc_refs > 0 to roots list */
172static void
173move_roots(PyGC_Head *containers, PyGC_Head *roots)
174{
175 PyGC_Head *next;
176 PyGC_Head *gc = containers->gc_next;
177 while (gc != containers) {
178 next = gc->gc_next;
179 if (gc->gc_refs > 0) {
180 gc_list_remove(gc);
181 gc_list_append(gc, roots);
182 gc->gc_refs = GC_MOVED;
183 }
184 gc = next;
185 }
186}
187
188static int
189visit_reachable(PyObject *op, PyGC_Head *roots)
190{
191 if (PyObject_IS_GC(op)) {
192 PyGC_Head *gc = PyObject_AS_GC(op);
193 if (gc && gc->gc_refs != GC_MOVED) {
194 gc_list_remove(gc);
195 gc_list_append(gc, roots);
196 gc->gc_refs = GC_MOVED;
197 }
198 }
199 return 0;
200}
201
202/* Move objects referenced from reachable to reachable set. */
203static void
204move_root_reachable(PyGC_Head *reachable)
205{
206 traverseproc traverse;
207 PyGC_Head *gc = reachable->gc_next;
208 for (; gc != reachable; gc=gc->gc_next) {
209 /* careful, reachable list is growing here */
210 PyObject *op = PyObject_FROM_GC(gc);
211 traverse = op->ob_type->tp_traverse;
212 (void) traverse(op,
213 (visitproc)visit_reachable,
214 (void *)reachable);
215 }
216}
217
218/* move all objects with finalizers (instances with __del__) */
219static void
220move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
221{
222 PyGC_Head *next;
223 PyGC_Head *gc = unreachable->gc_next;
224 static PyObject *delstr;
225 if (delstr == NULL) {
226 delstr = PyString_InternFromString("__del__");
227 }
228 for (; gc != unreachable; gc=next) {
229 PyObject *op = PyObject_FROM_GC(gc);
230 next = gc->gc_next;
231 if (PyInstance_Check(op) && PyObject_HasAttr(op, delstr)) {
232 gc_list_remove(gc);
233 gc_list_append(gc, finalizers);
234 }
235 }
236}
237
238
239/* called by tp_traverse */
240static int
241visit_finalizer_reachable(PyObject *op, PyGC_Head *finalizers)
242{
243 if (PyObject_IS_GC(op)) {
244 PyGC_Head *gc = PyObject_AS_GC(op);
245 if (gc && gc->gc_refs != GC_MOVED) {
246 gc_list_remove(gc);
247 gc_list_append(gc, finalizers);
248 gc->gc_refs = GC_MOVED;
249 }
250 }
251 return 0;
252}
253
254/* Move objects referenced from roots to roots */
255static void
256move_finalizer_reachable(PyGC_Head *finalizers)
257{
258 traverseproc traverse;
259 PyGC_Head *gc = finalizers->gc_next;
260 for (; gc != finalizers; gc=gc->gc_next) {
261 /* careful, finalizers list is growing here */
262 traverse = PyObject_FROM_GC(gc)->ob_type->tp_traverse;
263 (void) traverse(PyObject_FROM_GC(gc),
264 (visitproc)visit_finalizer_reachable,
265 (void *)finalizers);
266 }
267}
268
269static void
270debug_instance(PyObject *output, char *msg, PyInstanceObject *inst)
271{
272 char buf[200];
273 char *cname;
274 /* be careful not to create new dictionaries */
275 PyObject *classname = inst->in_class->cl_name;
276 if (classname != NULL && PyString_Check(classname))
277 cname = PyString_AsString(classname);
278 else
279 cname = "?";
Barry Warsaw35e459c2000-07-12 05:18:36 +0000280 sprintf(buf, "gc: %s<%.100s instance at %p>\n", msg, cname, inst);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000281 PyFile_WriteString(buf, output);
282}
283
284static void
285debug_cycle(PyObject *output, char *msg, PyObject *op)
286{
287 if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
288 debug_instance(output, msg, (PyInstanceObject *)op);
289 } else if (debug & DEBUG_OBJECTS) {
290 char buf[200];
Barry Warsaw35e459c2000-07-12 05:18:36 +0000291 sprintf(buf, "gc: %s<%.100s %p>\n", msg,
292 op->ob_type->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000293 PyFile_WriteString(buf, output);
294 }
295}
296
297/* Handle uncollectable garbage (cycles with finalizers). */
298static void
299handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
300{
301 PyGC_Head *gc;
302 if (garbage == NULL) {
303 garbage = PyList_New(0);
304 }
305 for (gc = finalizers->gc_next; gc != finalizers;
306 gc = finalizers->gc_next) {
307 PyObject *op = PyObject_FROM_GC(gc);
308 /* Add all instances to a Python accessible list of garbage */
309 if (PyInstance_Check(op)) {
310 PyList_Append(garbage, op);
311 }
312 /* We assume that all objects in finalizers are reachable from
313 * instances. Once we add the instances to the garbage list
314 * everything is reachable from Python again. */
315 gc_list_remove(gc);
316 gc_list_append(gc, old);
317 }
318}
319
320/* Break reference cycles by clearing the containers involved. This is
321 * tricky business as the lists can be changing and we don't know which
322 * objects may be freed. It is possible I screwed something up here. */
323static void
324delete_garbage(PyGC_Head *unreachable, PyGC_Head *old)
325{
326 inquiry clear;
327
328 while (unreachable->gc_next != unreachable) {
329 PyGC_Head *gc = unreachable->gc_next;
330 PyObject *op = PyObject_FROM_GC(gc);
331 /*
332 PyList_Append(garbage, op);
333 */
334 if ((clear = op->ob_type->tp_clear) != NULL) {
335 Py_INCREF(op);
336 clear((PyObject *)op);
337 Py_DECREF(op);
338 }
339 /* only try to call tp_clear once for each object */
340 if (unreachable->gc_next == gc) {
341 /* still alive, move it, it may die later */
342 gc_list_remove(gc);
343 gc_list_append(gc, old);
344 }
345 }
346}
347
348/* This is the main function. Read this to understand how the
349 * collection process works. */
350static long
351collect(PyGC_Head *young, PyGC_Head *old)
352{
353 long n = 0;
354 long m = 0;
355 PyGC_Head reachable;
356 PyGC_Head unreachable;
357 PyGC_Head finalizers;
358 PyGC_Head *gc;
359 PyObject *output = NULL;
360
361 if (debug) {
362 output = PySys_GetObject("stderr");
363 }
364 if (debug & DEBUG_STATS) {
365 char buf[100];
366 sprintf(buf, "gc: collecting generation %d...\n", generation);
367 PyFile_WriteString(buf,output);
Fred Drakeb35de5b2000-07-11 14:37:41 +0000368 sprintf(buf, "gc: objects in each generation: %ld %ld %ld\n",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000369 gc_list_size(&generation0),
370 gc_list_size(&generation1),
371 gc_list_size(&generation2));
372 PyFile_WriteString(buf,output);
373 }
374
375 /* Using ob_refcnt and gc_refs, calculate which objects in the
376 * container set are reachable from outside the set (ie. have a
377 * refcount greater than 0 when all the references within the
378 * set are taken into account */
379 update_refs(young);
380 subtract_refs(young);
381
382 /* Move everything reachable from outside the set into the
383 * reachable set (ie. gc_refs > 0). Next, move everything
384 * reachable from objects in the reachable set. */
385 gc_list_init(&reachable);
386 move_roots(young, &reachable);
387 move_root_reachable(&reachable);
388
389 /* move unreachable objects to a temporary list, new objects can be
390 * allocated after this point */
391 gc_list_init(&unreachable);
392 gc_list_move(young, &unreachable);
393
394 /* move reachable objects to next generation */
395 gc_list_merge(&reachable, old);
396
397 /* Move objects reachable from finalizers, we can't safely delete
398 * them. Python programmers should take care not to create such
399 * things. For Python finalizers means instance objects with
400 * __del__ methods. */
401 gc_list_init(&finalizers);
402 move_finalizers(&unreachable, &finalizers);
403 move_finalizer_reachable(&finalizers);
404
405 /* Collect statistics on collectable objects found and print
406 * debugging information. */
407 for (gc = unreachable.gc_next; gc != &unreachable;
408 gc = gc->gc_next) {
409 m++;
410 if (output != NULL && (debug & DEBUG_COLLECTABLE)) {
411 debug_cycle(output, "collectable ", PyObject_FROM_GC(gc));
412 }
413 }
414 /* call tp_clear on objects in the collectable set. This will cause
415 * the reference cycles to be broken. It may also cause some objects in
416 * finalizers to be freed */
417 delete_garbage(&unreachable, old);
418
419 /* Collect statistics on uncollectable objects found and print
420 * debugging information. */
421 for (gc = finalizers.gc_next; gc != &finalizers;
422 gc = gc->gc_next) {
423 n++;
424 if (output != NULL && (debug & DEBUG_UNCOLLECTABLE)) {
425 debug_cycle(output, "uncollectable ", PyObject_FROM_GC(gc));
426 }
427 }
428 if (output != NULL && (debug & DEBUG_STATS)) {
429 if (m == 0 && n == 0) {
430 PyFile_WriteString("gc: done.\n", output);
431 } else {
432 char buf[200];
433 sprintf(buf,
Fred Drakeb35de5b2000-07-11 14:37:41 +0000434 "gc: done, %ld unreachable, %ld uncollectable.\n",
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000435 n+m, n);
436 PyFile_WriteString(buf, output);
437 }
438 }
439
440 /* Append instances in the uncollectable set to a Python
441 * reachable list of garbage. The programmer has to deal with
442 * this if they insist on creating this type of structure. */
443 handle_finalizers(&finalizers, old);
444
445 allocated = 0;
446 PyErr_Clear(); /* in case writing to sys.stderr failed */
447 return n+m;
448}
449
450static long
451collect_generations(void)
452{
453 static long collections0 = 0;
454 static long collections1 = 0;
Vladimir Marangozovb16714b2000-07-10 05:37:39 +0000455 long n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000456
457
458 if (collections1 > threshold2) {
459 generation = 2;
460 gc_list_merge(&generation0, &generation2);
461 gc_list_merge(&generation1, &generation2);
462 if (generation2.gc_next != &generation2) {
463 n = collect(&generation2, &generation2);
464 }
465 collections1 = 0;
466 } else if (collections0 > threshold1) {
467 generation = 1;
468 collections1++;
469 gc_list_merge(&generation0, &generation1);
470 if (generation1.gc_next != &generation1) {
471 n = collect(&generation1, &generation2);
472 }
473 collections0 = 0;
474 } else {
475 generation = 0;
476 collections0++;
477 if (generation0.gc_next != &generation0) {
478 n = collect(&generation0, &generation1);
479 }
480 }
481 return n;
482}
483
484void
485_PyGC_Insert(PyObject *op)
486{
487 /* collection lock since collecting may cause allocations */
488 static int collecting = 0;
489
490#ifdef Py_DEBUG
491 if (!PyObject_IS_GC(op)) {
492 abort();
493 }
494#endif
495 if (threshold0 && allocated > threshold0 && !collecting) {
496 collecting++;
497 collect_generations();
498 collecting--;
499 }
500 allocated++;
501 gc_list_append(PyObject_AS_GC(op), &generation0);
502}
503
504void
505_PyGC_Remove(PyObject *op)
506{
507 PyGC_Head *g = PyObject_AS_GC(op);
508#ifdef Py_DEBUG
509 if (!PyObject_IS_GC(op)) {
510 abort();
511 }
512#endif
513 gc_list_remove(g);
514 if (allocated > 0) {
515 allocated--;
516 }
517}
518
519
520static char collect__doc__[] =
521"collect() -> n\n"
522"\n"
523"Run a full collection. The number of unreachable objects is returned.\n"
524;
525
526static PyObject *
Peter Schneider-Kamp8bc8f0d2000-07-10 17:15:07 +0000527Py_collect(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000528{
529 long n;
530
Fred Drakecc1be242000-07-12 04:42:23 +0000531 if (!PyArg_ParseTuple(args, ":collect")) /* check no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000532 return NULL;
533
534 generation = 2;
535 gc_list_merge(&generation0, &generation2);
536 gc_list_merge(&generation1, &generation2);
537 n = collect(&generation2, &generation2);
538
539 return Py_BuildValue("i", n);
540}
541
542static char set_debug__doc__[] =
543"set_debug(flags) -> None\n"
544"\n"
545"Set the garbage collection debugging flags. Debugging information is\n"
546"written to sys.stderr.\n"
547"\n"
548"flags is an integer and can have the following bits turned on:\n"
549"\n"
550" DEBUG_STATS - Print statistics during collection.\n"
551" DEBUG_COLLECTABLE - Print collectable objects found.\n"
552" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
553" DEBUG_INSTANCES - Print instance objects.\n"
554" DEBUG_OBJECTS - Print objects other than instances.\n"
555" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n"
556;
557
558static PyObject *
Peter Schneider-Kamp8bc8f0d2000-07-10 17:15:07 +0000559Py_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000560{
Fred Drakecc1be242000-07-12 04:42:23 +0000561 if (!PyArg_ParseTuple(args, "l:get_debug", &debug))
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000562 return NULL;
563
564 Py_INCREF(Py_None);
565 return Py_None;
566}
567
568static char get_debug__doc__[] =
569"get_debug() -> flags\n"
570"\n"
571"Get the garbage collection debugging flags.\n"
572;
573
574static PyObject *
Peter Schneider-Kamp8bc8f0d2000-07-10 17:15:07 +0000575Py_get_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000576{
Fred Drakecc1be242000-07-12 04:42:23 +0000577 if (!PyArg_ParseTuple(args, ":get_debug")) /* no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000578 return NULL;
579
580 return Py_BuildValue("i", debug);
581}
582
583static char set_thresh__doc__[] =
584"set_threshold(threshold0, [threhold1, threshold2]) -> None\n"
585"\n"
586"Sets the collection thresholds. Setting threshold0 to zero disables\n"
587"collection.\n"
588;
589
590static PyObject *
Peter Schneider-Kamp8bc8f0d2000-07-10 17:15:07 +0000591Py_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000592{
Fred Drakecc1be242000-07-12 04:42:23 +0000593 if (!PyArg_ParseTuple(args, "i|ii:set_threshold", &threshold0,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000594 &threshold1, &threshold2))
595 return NULL;
596
597 Py_INCREF(Py_None);
598 return Py_None;
599}
600
601static char get_thresh__doc__[] =
602"get_threshold() -> (threshold0, threshold1, threshold2)\n"
603"\n"
604"Return the current collection thresholds\n"
605;
606
607static PyObject *
Peter Schneider-Kamp8bc8f0d2000-07-10 17:15:07 +0000608Py_get_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000609{
Fred Drakecc1be242000-07-12 04:42:23 +0000610 if (!PyArg_ParseTuple(args, ":get_threshold")) /* no args */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000611 return NULL;
612
613 return Py_BuildValue("(iii)", threshold0, threshold1, threshold2);
614}
615
616
617static char gc__doc__ [] =
618"This module provides access to the garbage collector for reference cycles.\n"
619"\n"
620"collect() -- Do a full collection right now.\n"
621"set_debug() -- Set debugging flags.\n"
622"get_debug() -- Get debugging flags.\n"
623"set_threshold() -- Set the collection thresholds.\n"
624"get_threshold() -- Return the current the collection thresholds.\n"
625;
626
627static PyMethodDef GcMethods[] = {
628 {"set_debug", Py_set_debug, METH_VARARGS, set_debug__doc__},
629 {"get_debug", Py_get_debug, METH_VARARGS, get_debug__doc__},
630 {"set_threshold", Py_set_thresh, METH_VARARGS, set_thresh__doc__},
631 {"get_threshold", Py_get_thresh, METH_VARARGS, get_thresh__doc__},
632 {"collect", Py_collect, METH_VARARGS, collect__doc__},
633 {NULL, NULL} /* Sentinel */
634};
635
636void
637initgc(void)
638{
639 PyObject *m;
640 PyObject *d;
641
642 m = Py_InitModule4("gc",
643 GcMethods,
644 gc__doc__,
645 NULL,
646 PYTHON_API_VERSION);
647 d = PyModule_GetDict(m);
648 if (garbage == NULL) {
649 garbage = PyList_New(0);
650 }
651 PyDict_SetItemString(d, "garbage", garbage);
652 PyDict_SetItemString(d, "DEBUG_STATS",
653 PyInt_FromLong(DEBUG_STATS));
654 PyDict_SetItemString(d, "DEBUG_COLLECTABLE",
655 PyInt_FromLong(DEBUG_COLLECTABLE));
656 PyDict_SetItemString(d, "DEBUG_UNCOLLECTABLE",
657 PyInt_FromLong(DEBUG_UNCOLLECTABLE));
658 PyDict_SetItemString(d, "DEBUG_INSTANCES",
659 PyInt_FromLong(DEBUG_INSTANCES));
660 PyDict_SetItemString(d, "DEBUG_OBJECTS",
661 PyInt_FromLong(DEBUG_OBJECTS));
662 PyDict_SetItemString(d, "DEBUG_LEAK",
663 PyInt_FromLong(DEBUG_LEAK));
664}
665
666#endif /* WITH_CYCLE_GC */