blob: 832e27ebe664e20dc248f81da0504fba70a04912 [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/
Neil Schemenauera7024e92008-07-15 19:24:01 +000012
13 The following mailing list threads provide a historical perspective on
14 the design of this module. Note that a fair amount of refinement has
15 occurred since those discussions.
16
17 http://mail.python.org/pipermail/python-dev/2000-March/002385.html
18 http://mail.python.org/pipermail/python-dev/2000-March/002434.html
19 http://mail.python.org/pipermail/python-dev/2000-March/002497.html
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000020
21 For a highlevel view of the collection process, read the collect
22 function.
23
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000024*/
25
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000026#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060027#include "internal/mem.h"
28#include "internal/pystate.h"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000029#include "frameobject.h" /* for PyFrame_ClearFreeList */
Łukasz Langaa785c872016-09-09 17:37:37 -070030#include "pydtrace.h"
Victor Stinner7181dec2015-03-27 17:47:53 +010031#include "pytime.h" /* for _PyTime_GetMonotonicClock() */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000032
Serhiy Storchaka93260282017-02-04 11:19:59 +020033/*[clinic input]
34module gc
35[clinic start generated code]*/
36/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b5c9690ecc842d79]*/
37
Neil Schemenauer43411b52001-08-30 00:05:51 +000038/* Get an object's GC head */
39#define AS_GC(o) ((PyGC_Head *)(o)-1)
40
41/* Get the object given the GC head */
42#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
43
Tim Peters6fc13d92002-07-02 18:12:35 +000044/* Python string to use if unhandled exception occurs */
Tim Petersbf384c22003-04-06 00:11:39 +000045static PyObject *gc_str = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000046
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000047/* set for debugging information */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048#define DEBUG_STATS (1<<0) /* print collection statistics */
49#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
50#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
51#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
52#define DEBUG_LEAK DEBUG_COLLECTABLE | \
53 DEBUG_UNCOLLECTABLE | \
54 DEBUG_SAVEALL
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000055
Eric Snow2ebc5ce2017-09-07 23:51:28 -060056#define GEN_HEAD(n) (&_PyRuntime.gc.generations[n].head)
Antoine Pitroud4156c12012-10-30 22:43:19 +010057
Eric Snow2ebc5ce2017-09-07 23:51:28 -060058void
59_PyGC_Initialize(struct _gc_runtime_state *state)
60{
61 state->enabled = 1; /* automatic collection enabled? */
62
63#define _GEN_HEAD(n) (&state->generations[n].head)
64 struct gc_generation generations[NUM_GENERATIONS] = {
65 /* PyGC_Head, threshold, count */
66 {{{_GEN_HEAD(0), _GEN_HEAD(0), 0}}, 700, 0},
67 {{{_GEN_HEAD(1), _GEN_HEAD(1), 0}}, 10, 0},
68 {{{_GEN_HEAD(2), _GEN_HEAD(2), 0}}, 10, 0},
69 };
70 for (int i = 0; i < NUM_GENERATIONS; i++) {
71 state->generations[i] = generations[i];
72 };
73 state->generation0 = GEN_HEAD(0);
74}
Antoine Pitroud4156c12012-10-30 22:43:19 +010075
Tim Peters6fc13d92002-07-02 18:12:35 +000076/*--------------------------------------------------------------------------
77gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +000078
Tim Peters6fc13d92002-07-02 18:12:35 +000079Between collections, every gc'ed object has one of two gc_refs values:
80
81GC_UNTRACKED
82 The initial state; objects returned by PyObject_GC_Malloc are in this
83 state. The object doesn't live in any generation list, and its
84 tp_traverse slot must not be called.
85
86GC_REACHABLE
87 The object lives in some generation list, and its tp_traverse is safe to
88 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
89 is called.
90
91During a collection, gc_refs can temporarily take on other states:
92
93>= 0
94 At the start of a collection, update_refs() copies the true refcount
95 to gc_refs, for each object in the generation being collected.
96 subtract_refs() then adjusts gc_refs so that it equals the number of
97 times an object is referenced directly from outside the generation
98 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +000099 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000100
101GC_TENTATIVELY_UNREACHABLE
102 move_unreachable() then moves objects not reachable (whether directly or
103 indirectly) from outside the generation into an "unreachable" set.
104 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
105 again. Objects that are found to be unreachable have gc_refs set to
106 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
107 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
108 transition back to GC_REACHABLE.
109
110 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
111 for collection. If it's decided not to collect such an object (e.g.,
112 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
113----------------------------------------------------------------------------
114*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
116#define GC_REACHABLE _PyGC_REFS_REACHABLE
117#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000118
Antoine Pitrou796564c2013-07-30 19:59:21 +0200119#define IS_TRACKED(o) (_PyGC_REFS(o) != GC_UNTRACKED)
120#define IS_REACHABLE(o) (_PyGC_REFS(o) == GC_REACHABLE)
Tim Peters19b74c72002-07-01 03:52:19 +0000121#define IS_TENTATIVELY_UNREACHABLE(o) ( \
Antoine Pitrou796564c2013-07-30 19:59:21 +0200122 _PyGC_REFS(o) == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000123
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000124/*** list functions ***/
125
126static void
127gc_list_init(PyGC_Head *list)
128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 list->gc.gc_prev = list;
130 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000131}
132
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000133static int
134gc_list_is_empty(PyGC_Head *list)
135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000136 return (list->gc.gc_next == list);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000137}
138
Tim Peterse2d59182004-11-01 01:39:08 +0000139#if 0
140/* This became unused after gc_list_move() was introduced. */
141/* Append `node` to `list`. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000142static void
143gc_list_append(PyGC_Head *node, PyGC_Head *list)
144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000145 node->gc.gc_next = list;
146 node->gc.gc_prev = list->gc.gc_prev;
147 node->gc.gc_prev->gc.gc_next = node;
148 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000149}
Tim Peterse2d59182004-11-01 01:39:08 +0000150#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000151
Tim Peterse2d59182004-11-01 01:39:08 +0000152/* Remove `node` from the gc list it's currently in. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000153static void
154gc_list_remove(PyGC_Head *node)
155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
157 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
158 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000159}
160
Tim Peterse2d59182004-11-01 01:39:08 +0000161/* Move `node` from the gc list it's currently in (which is not explicitly
162 * named here) to the end of `list`. This is semantically the same as
163 * gc_list_remove(node) followed by gc_list_append(node, list).
164 */
165static void
166gc_list_move(PyGC_Head *node, PyGC_Head *list)
167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 PyGC_Head *new_prev;
169 PyGC_Head *current_prev = node->gc.gc_prev;
170 PyGC_Head *current_next = node->gc.gc_next;
171 /* Unlink from current list. */
172 current_prev->gc.gc_next = current_next;
173 current_next->gc.gc_prev = current_prev;
174 /* Relink at end of new list. */
175 new_prev = node->gc.gc_prev = list->gc.gc_prev;
176 new_prev->gc.gc_next = list->gc.gc_prev = node;
177 node->gc.gc_next = list;
Tim Peterse2d59182004-11-01 01:39:08 +0000178}
179
180/* append list `from` onto list `to`; `from` becomes an empty list */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000181static void
182gc_list_merge(PyGC_Head *from, PyGC_Head *to)
183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 PyGC_Head *tail;
185 assert(from != to);
186 if (!gc_list_is_empty(from)) {
187 tail = to->gc.gc_prev;
188 tail->gc.gc_next = from->gc.gc_next;
189 tail->gc.gc_next->gc.gc_prev = tail;
190 to->gc.gc_prev = from->gc.gc_prev;
191 to->gc.gc_prev->gc.gc_next = to;
192 }
193 gc_list_init(from);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000194}
195
Neal Norwitz7b216c52006-03-04 20:01:53 +0000196static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000197gc_list_size(PyGC_Head *list)
198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 PyGC_Head *gc;
200 Py_ssize_t n = 0;
201 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
202 n++;
203 }
204 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000205}
206
Tim Peters259272b2003-04-06 19:41:39 +0000207/* Append objects in a GC list to a Python list.
208 * Return 0 if all OK, < 0 if error (out of memory for list).
209 */
210static int
211append_objects(PyObject *py_list, PyGC_Head *gc_list)
212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 PyGC_Head *gc;
214 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
215 PyObject *op = FROM_GC(gc);
216 if (op != py_list) {
217 if (PyList_Append(py_list, op)) {
218 return -1; /* exception */
219 }
220 }
221 }
222 return 0;
Tim Peters259272b2003-04-06 19:41:39 +0000223}
224
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000225/*** end of list stuff ***/
226
227
Tim Peters19b74c72002-07-01 03:52:19 +0000228/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
229 * in containers, and is GC_REACHABLE for all tracked gc objects not in
230 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000231 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000232static void
233update_refs(PyGC_Head *containers)
234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyGC_Head *gc = containers->gc.gc_next;
236 for (; gc != containers; gc = gc->gc.gc_next) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200237 assert(_PyGCHead_REFS(gc) == GC_REACHABLE);
238 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 /* Python's cyclic gc should never see an incoming refcount
240 * of 0: if something decref'ed to 0, it should have been
241 * deallocated immediately at that time.
242 * Possible cause (if the assert triggers): a tp_dealloc
243 * routine left a gc-aware object tracked during its teardown
244 * phase, and did something-- or allowed something to happen --
245 * that called back into Python. gc can trigger then, and may
246 * see the still-tracked dying object. Before this assert
247 * was added, such mistakes went on to allow gc to try to
248 * delete the object again. In a debug build, that caused
249 * a mysterious segfault, when _Py_ForgetReference tried
250 * to remove the object from the doubly-linked list of all
251 * objects a second time. In a release build, an actual
252 * double deallocation occurred, which leads to corruption
253 * of the allocator's internal bookkeeping pointers. That's
254 * so serious that maybe this should be a release-build
255 * check instead of an assert?
256 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200257 assert(_PyGCHead_REFS(gc) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000259}
260
Tim Peters19b74c72002-07-01 03:52:19 +0000261/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000262static int
263visit_decref(PyObject *op, void *data)
264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 assert(op != NULL);
266 if (PyObject_IS_GC(op)) {
267 PyGC_Head *gc = AS_GC(op);
268 /* We're only interested in gc_refs for objects in the
269 * generation being collected, which can be recognized
270 * because only they have positive gc_refs.
271 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200272 assert(_PyGCHead_REFS(gc) != 0); /* else refcount was too small */
273 if (_PyGCHead_REFS(gc) > 0)
274 _PyGCHead_DECREF(gc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 }
276 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000277}
278
Tim Peters19b74c72002-07-01 03:52:19 +0000279/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
280 * for all objects in containers, and is GC_REACHABLE for all tracked gc
281 * objects not in containers. The ones with gc_refs > 0 are directly
282 * reachable from outside containers, and so can't be collected.
283 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000284static void
285subtract_refs(PyGC_Head *containers)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 traverseproc traverse;
288 PyGC_Head *gc = containers->gc.gc_next;
289 for (; gc != containers; gc=gc->gc.gc_next) {
290 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
291 (void) traverse(FROM_GC(gc),
292 (visitproc)visit_decref,
293 NULL);
294 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000295}
296
Tim Peters19b74c72002-07-01 03:52:19 +0000297/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000298static int
Tim Peters19b74c72002-07-01 03:52:19 +0000299visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 if (PyObject_IS_GC(op)) {
302 PyGC_Head *gc = AS_GC(op);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200303 const Py_ssize_t gc_refs = _PyGCHead_REFS(gc);
Tim Peters19b74c72002-07-01 03:52:19 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (gc_refs == 0) {
306 /* This is in move_unreachable's 'young' list, but
307 * the traversal hasn't yet gotten to it. All
308 * we need to do is tell move_unreachable that it's
309 * reachable.
310 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200311 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 }
313 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
314 /* This had gc_refs = 0 when move_unreachable got
315 * to it, but turns out it's reachable after all.
316 * Move it back to move_unreachable's 'young' list,
317 * and move_unreachable will eventually get to it
318 * again.
319 */
320 gc_list_move(gc, reachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200321 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 }
323 /* Else there's nothing to do.
324 * If gc_refs > 0, it must be in move_unreachable's 'young'
325 * list, and move_unreachable will eventually get to it.
326 * If gc_refs == GC_REACHABLE, it's either in some other
327 * generation so we don't care about it, or move_unreachable
328 * already dealt with it.
329 * If gc_refs == GC_UNTRACKED, it must be ignored.
330 */
331 else {
332 assert(gc_refs > 0
333 || gc_refs == GC_REACHABLE
334 || gc_refs == GC_UNTRACKED);
335 }
336 }
337 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000338}
339
Tim Peters19b74c72002-07-01 03:52:19 +0000340/* Move the unreachable objects from young to unreachable. After this,
341 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
342 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
343 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
344 * All objects in young after this are directly or indirectly reachable
345 * from outside the original young; and all objects in unreachable are
346 * not.
Tim Peters88396172002-06-30 17:56:40 +0000347 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000348static void
Tim Peters19b74c72002-07-01 03:52:19 +0000349move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyGC_Head *gc = young->gc.gc_next;
Tim Peters19b74c72002-07-01 03:52:19 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* Invariants: all objects "to the left" of us in young have gc_refs
354 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
355 * from outside the young list as it was at entry. All other objects
356 * from the original young "to the left" of us are in unreachable now,
357 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
358 * left of us in 'young' now have been scanned, and no objects here
359 * or to the right have been scanned yet.
360 */
Tim Peters19b74c72002-07-01 03:52:19 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 while (gc != young) {
363 PyGC_Head *next;
Tim Peters19b74c72002-07-01 03:52:19 +0000364
Antoine Pitrou796564c2013-07-30 19:59:21 +0200365 if (_PyGCHead_REFS(gc)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* gc is definitely reachable from outside the
367 * original 'young'. Mark it as such, and traverse
368 * its pointers to find any other objects that may
369 * be directly reachable from it. Note that the
370 * call to tp_traverse may append objects to young,
371 * so we have to wait until it returns to determine
372 * the next object to visit.
373 */
374 PyObject *op = FROM_GC(gc);
375 traverseproc traverse = Py_TYPE(op)->tp_traverse;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200376 assert(_PyGCHead_REFS(gc) > 0);
377 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 (void) traverse(op,
379 (visitproc)visit_reachable,
380 (void *)young);
381 next = gc->gc.gc_next;
382 if (PyTuple_CheckExact(op)) {
383 _PyTuple_MaybeUntrack(op);
384 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 }
386 else {
387 /* This *may* be unreachable. To make progress,
388 * assume it is. gc isn't directly reachable from
389 * any object we've already traversed, but may be
390 * reachable from an object we haven't gotten to yet.
391 * visit_reachable will eventually move gc back into
392 * young if that's so, and we'll see it again.
393 */
394 next = gc->gc.gc_next;
395 gc_list_move(gc, unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200396 _PyGCHead_SET_REFS(gc, GC_TENTATIVELY_UNREACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 }
398 gc = next;
399 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000400}
401
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200402/* Try to untrack all currently tracked dictionaries */
403static void
404untrack_dicts(PyGC_Head *head)
405{
406 PyGC_Head *next, *gc = head->gc.gc_next;
407 while (gc != head) {
408 PyObject *op = FROM_GC(gc);
409 next = gc->gc.gc_next;
410 if (PyDict_CheckExact(op))
411 _PyDict_MaybeUntrack(op);
412 gc = next;
413 }
414}
415
Antoine Pitrou796564c2013-07-30 19:59:21 +0200416/* Return true if object has a pre-PEP 442 finalization method. */
Neil Schemenauera765c122001-11-01 17:35:23 +0000417static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200418has_legacy_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000419{
Antoine Pitrou796564c2013-07-30 19:59:21 +0200420 return op->ob_type->tp_del != NULL;
Neil Schemenauera765c122001-11-01 17:35:23 +0000421}
422
Antoine Pitrou796564c2013-07-30 19:59:21 +0200423/* Move the objects in unreachable with tp_del slots into `finalizers`.
Tim Petersead8b7a2004-10-30 23:09:22 +0000424 * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the
425 * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000426 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000427static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200428move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 PyGC_Head *gc;
431 PyGC_Head *next;
Tim Petersf6b80452003-04-07 19:21:15 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 /* March over unreachable. Move objects with finalizers into
434 * `finalizers`.
435 */
436 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
437 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 assert(IS_TENTATIVELY_UNREACHABLE(op));
440 next = gc->gc.gc_next;
Tim Petersf6ae7a42003-04-05 18:40:50 +0000441
Antoine Pitrou796564c2013-07-30 19:59:21 +0200442 if (has_legacy_finalizer(op)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 gc_list_move(gc, finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200444 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 }
446 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000447}
448
Antoine Pitrou796564c2013-07-30 19:59:21 +0200449/* A traversal callback for move_legacy_finalizer_reachable. */
Tim Peters19b74c72002-07-01 03:52:19 +0000450static int
451visit_move(PyObject *op, PyGC_Head *tolist)
452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (PyObject_IS_GC(op)) {
454 if (IS_TENTATIVELY_UNREACHABLE(op)) {
455 PyGC_Head *gc = AS_GC(op);
456 gc_list_move(gc, tolist);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200457 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 }
459 }
460 return 0;
Tim Peters19b74c72002-07-01 03:52:19 +0000461}
462
463/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersf6b80452003-04-07 19:21:15 +0000464 * into finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000465 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000466static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200467move_legacy_finalizer_reachable(PyGC_Head *finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 traverseproc traverse;
470 PyGC_Head *gc = finalizers->gc.gc_next;
471 for (; gc != finalizers; gc = gc->gc.gc_next) {
472 /* Note that the finalizers list may grow during this. */
473 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
474 (void) traverse(FROM_GC(gc),
475 (visitproc)visit_move,
476 (void *)finalizers);
477 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000478}
479
Tim Petersead8b7a2004-10-30 23:09:22 +0000480/* Clear all weakrefs to unreachable objects, and if such a weakref has a
481 * callback, invoke it if necessary. Note that it's possible for such
482 * weakrefs to be outside the unreachable set -- indeed, those are precisely
483 * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
484 * overview & some details. Some weakrefs with callbacks may be reclaimed
485 * directly by this routine; the number reclaimed is the return value. Other
486 * weakrefs with callbacks may be moved into the `old` generation. Objects
487 * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
488 * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
489 * no object in `unreachable` is weakly referenced anymore.
Tim Peters403a2032003-11-20 21:21:46 +0000490 */
491static int
Tim Petersead8b7a2004-10-30 23:09:22 +0000492handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
Tim Peters403a2032003-11-20 21:21:46 +0000493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 PyGC_Head *gc;
495 PyObject *op; /* generally FROM_GC(gc) */
496 PyWeakReference *wr; /* generally a cast of op */
497 PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
498 PyGC_Head *next;
499 int num_freed = 0;
Tim Peters403a2032003-11-20 21:21:46 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 gc_list_init(&wrcb_to_call);
Tim Peters403a2032003-11-20 21:21:46 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 /* Clear all weakrefs to the objects in unreachable. If such a weakref
504 * also has a callback, move it into `wrcb_to_call` if the callback
505 * needs to be invoked. Note that we cannot invoke any callbacks until
506 * all weakrefs to unreachable objects are cleared, lest the callback
507 * resurrect an unreachable object via a still-active weakref. We
508 * make another pass over wrcb_to_call, invoking callbacks, after this
509 * pass completes.
510 */
511 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
512 PyWeakReference **wrlist;
Tim Petersead8b7a2004-10-30 23:09:22 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 op = FROM_GC(gc);
515 assert(IS_TENTATIVELY_UNREACHABLE(op));
516 next = gc->gc.gc_next;
Tim Petersead8b7a2004-10-30 23:09:22 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
519 continue;
Tim Petersead8b7a2004-10-30 23:09:22 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 /* It supports weakrefs. Does it have any? */
522 wrlist = (PyWeakReference **)
523 PyObject_GET_WEAKREFS_LISTPTR(op);
Tim Petersead8b7a2004-10-30 23:09:22 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* `op` may have some weakrefs. March over the list, clear
526 * all the weakrefs, and move the weakrefs with callbacks
527 * that must be called into wrcb_to_call.
528 */
529 for (wr = *wrlist; wr != NULL; wr = *wrlist) {
530 PyGC_Head *wrasgc; /* AS_GC(wr) */
Tim Petersead8b7a2004-10-30 23:09:22 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 /* _PyWeakref_ClearRef clears the weakref but leaves
533 * the callback pointer intact. Obscure: it also
534 * changes *wrlist.
535 */
536 assert(wr->wr_object == op);
537 _PyWeakref_ClearRef(wr);
538 assert(wr->wr_object == Py_None);
539 if (wr->wr_callback == NULL)
540 continue; /* no callback */
Tim Petersead8b7a2004-10-30 23:09:22 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 /* Headache time. `op` is going away, and is weakly referenced by
543 * `wr`, which has a callback. Should the callback be invoked? If wr
544 * is also trash, no:
545 *
546 * 1. There's no need to call it. The object and the weakref are
547 * both going away, so it's legitimate to pretend the weakref is
548 * going away first. The user has to ensure a weakref outlives its
549 * referent if they want a guarantee that the wr callback will get
550 * invoked.
551 *
552 * 2. It may be catastrophic to call it. If the callback is also in
553 * cyclic trash (CT), then although the CT is unreachable from
554 * outside the current generation, CT may be reachable from the
555 * callback. Then the callback could resurrect insane objects.
556 *
557 * Since the callback is never needed and may be unsafe in this case,
558 * wr is simply left in the unreachable set. Note that because we
559 * already called _PyWeakref_ClearRef(wr), its callback will never
560 * trigger.
561 *
562 * OTOH, if wr isn't part of CT, we should invoke the callback: the
563 * weakref outlived the trash. Note that since wr isn't CT in this
564 * case, its callback can't be CT either -- wr acted as an external
565 * root to this generation, and therefore its callback did too. So
566 * nothing in CT is reachable from the callback either, so it's hard
567 * to imagine how calling it later could create a problem for us. wr
568 * is moved to wrcb_to_call in this case.
569 */
570 if (IS_TENTATIVELY_UNREACHABLE(wr))
571 continue;
572 assert(IS_REACHABLE(wr));
Tim Peterscc2a8662004-10-31 22:12:43 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 /* Create a new reference so that wr can't go away
575 * before we can process it again.
576 */
577 Py_INCREF(wr);
Tim Petersead8b7a2004-10-30 23:09:22 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Move wr to wrcb_to_call, for the next pass. */
580 wrasgc = AS_GC(wr);
581 assert(wrasgc != next); /* wrasgc is reachable, but
582 next isn't, so they can't
583 be the same */
584 gc_list_move(wrasgc, &wrcb_to_call);
585 }
586 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* Invoke the callbacks we decided to honor. It's safe to invoke them
589 * because they can't reference unreachable objects.
590 */
591 while (! gc_list_is_empty(&wrcb_to_call)) {
592 PyObject *temp;
593 PyObject *callback;
Tim Petersead8b7a2004-10-30 23:09:22 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 gc = wrcb_to_call.gc.gc_next;
596 op = FROM_GC(gc);
597 assert(IS_REACHABLE(op));
598 assert(PyWeakref_Check(op));
599 wr = (PyWeakReference *)op;
600 callback = wr->wr_callback;
601 assert(callback != NULL);
Tim Petersead8b7a2004-10-30 23:09:22 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 /* copy-paste of weakrefobject.c's handle_callback() */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100604 temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (temp == NULL)
606 PyErr_WriteUnraisable(callback);
607 else
608 Py_DECREF(temp);
Tim Petersead8b7a2004-10-30 23:09:22 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 /* Give up the reference we created in the first pass. When
611 * op's refcount hits 0 (which it may or may not do right now),
612 * op's tp_dealloc will decref op->wr_callback too. Note
613 * that the refcount probably will hit 0 now, and because this
614 * weakref was reachable to begin with, gc didn't already
615 * add it to its count of freed objects. Example: a reachable
616 * weak value dict maps some key to this reachable weakref.
617 * The callback removes this key->weakref mapping from the
618 * dict, leaving no other references to the weakref (excepting
619 * ours).
620 */
621 Py_DECREF(op);
622 if (wrcb_to_call.gc.gc_next == gc) {
623 /* object is still alive -- move it */
624 gc_list_move(gc, old);
625 }
626 else
627 ++num_freed;
628 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return num_freed;
Tim Peters403a2032003-11-20 21:21:46 +0000631}
632
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000633static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200634debug_cycle(const char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000635{
Victor Stinner499dfcf2011-03-21 13:26:24 +0100636 PySys_FormatStderr("gc: %s <%s %p>\n",
637 msg, Py_TYPE(op)->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000638}
639
Antoine Pitrou796564c2013-07-30 19:59:21 +0200640/* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
Tim Petersbf384c22003-04-06 00:11:39 +0000641 * only from such cycles).
Tim Petersf6b80452003-04-07 19:21:15 +0000642 * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
643 * garbage list (a Python list), else only the objects in finalizers with
644 * __del__ methods are appended to garbage. All objects in finalizers are
645 * merged into the old list regardless.
Tim Peters259272b2003-04-06 19:41:39 +0000646 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
647 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000648 */
Tim Peters259272b2003-04-06 19:41:39 +0000649static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200650handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersf6b80452003-04-07 19:21:15 +0000653
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600654 if (_PyRuntime.gc.garbage == NULL) {
655 _PyRuntime.gc.garbage = PyList_New(0);
656 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 Py_FatalError("gc couldn't create gc.garbage list");
658 }
659 for (; gc != finalizers; gc = gc->gc.gc_next) {
660 PyObject *op = FROM_GC(gc);
Tim Petersf6b80452003-04-07 19:21:15 +0000661
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600662 if ((_PyRuntime.gc.debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {
663 if (PyList_Append(_PyRuntime.gc.garbage, op) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 return -1;
665 }
666 }
Tim Petersf6b80452003-04-07 19:21:15 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 gc_list_merge(finalizers, old);
669 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000670}
671
Tim Peters5fbc7b12014-05-08 17:42:19 -0500672/* Run first-time finalizers (if any) on all the objects in collectable.
673 * Note that this may remove some (or even all) of the objects from the
674 * list, due to refcounts falling to 0.
675 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200676static void
Tim Peters5fbc7b12014-05-08 17:42:19 -0500677finalize_garbage(PyGC_Head *collectable)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200678{
679 destructor finalize;
Tim Peters5fbc7b12014-05-08 17:42:19 -0500680 PyGC_Head seen;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200681
Tim Peters5fbc7b12014-05-08 17:42:19 -0500682 /* While we're going through the loop, `finalize(op)` may cause op, or
683 * other objects, to be reclaimed via refcounts falling to zero. So
684 * there's little we can rely on about the structure of the input
685 * `collectable` list across iterations. For safety, we always take the
686 * first object in that list and move it to a temporary `seen` list.
687 * If objects vanish from the `collectable` and `seen` lists we don't
688 * care.
689 */
690 gc_list_init(&seen);
691
692 while (!gc_list_is_empty(collectable)) {
693 PyGC_Head *gc = collectable->gc.gc_next;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200694 PyObject *op = FROM_GC(gc);
Tim Peters5fbc7b12014-05-08 17:42:19 -0500695 gc_list_move(gc, &seen);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200696 if (!_PyGCHead_FINALIZED(gc) &&
Tim Peters5fbc7b12014-05-08 17:42:19 -0500697 PyType_HasFeature(Py_TYPE(op), Py_TPFLAGS_HAVE_FINALIZE) &&
698 (finalize = Py_TYPE(op)->tp_finalize) != NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200699 _PyGCHead_SET_FINALIZED(gc, 1);
700 Py_INCREF(op);
701 finalize(op);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200702 Py_DECREF(op);
703 }
704 }
Tim Peters5fbc7b12014-05-08 17:42:19 -0500705 gc_list_merge(&seen, collectable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200706}
707
708/* Walk the collectable list and check that they are really unreachable
709 from the outside (some objects could have been resurrected by a
710 finalizer). */
711static int
712check_garbage(PyGC_Head *collectable)
713{
714 PyGC_Head *gc;
715 for (gc = collectable->gc.gc_next; gc != collectable;
716 gc = gc->gc.gc_next) {
717 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
718 assert(_PyGCHead_REFS(gc) != 0);
719 }
720 subtract_refs(collectable);
721 for (gc = collectable->gc.gc_next; gc != collectable;
722 gc = gc->gc.gc_next) {
723 assert(_PyGCHead_REFS(gc) >= 0);
724 if (_PyGCHead_REFS(gc) != 0)
725 return -1;
726 }
727 return 0;
728}
729
730static void
731revive_garbage(PyGC_Head *collectable)
732{
733 PyGC_Head *gc;
734 for (gc = collectable->gc.gc_next; gc != collectable;
735 gc = gc->gc.gc_next) {
736 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
737 }
738}
739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000741 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000742 * objects may be freed. It is possible I screwed something up here.
743 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000744static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000745delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 inquiry clear;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 while (!gc_list_is_empty(collectable)) {
750 PyGC_Head *gc = collectable->gc.gc_next;
751 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000752
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600753 if (_PyRuntime.gc.debug & DEBUG_SAVEALL) {
754 PyList_Append(_PyRuntime.gc.garbage, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 }
756 else {
757 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
758 Py_INCREF(op);
759 clear(op);
760 Py_DECREF(op);
761 }
762 }
763 if (collectable->gc.gc_next == gc) {
764 /* object is still alive, move it, it may die later */
765 gc_list_move(gc, old);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200766 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 }
768 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000769}
770
Christian Heimesa156e092008-02-16 07:38:31 +0000771/* Clear all free lists
772 * All free lists are cleared during the collection of the highest generation.
773 * Allocated items in the free list may keep a pymalloc arena occupied.
774 * Clearing the free lists may give back memory to the OS earlier.
775 */
776static void
777clear_freelists(void)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 (void)PyMethod_ClearFreeList();
780 (void)PyFrame_ClearFreeList();
781 (void)PyCFunction_ClearFreeList();
782 (void)PyTuple_ClearFreeList();
783 (void)PyUnicode_ClearFreeList();
784 (void)PyFloat_ClearFreeList();
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100785 (void)PyList_ClearFreeList();
786 (void)PyDict_ClearFreeList();
Antoine Pitrou093ce9c2011-12-16 11:24:27 +0100787 (void)PySet_ClearFreeList();
Yury Selivanoveb636452016-09-08 22:01:51 -0700788 (void)PyAsyncGen_ClearFreeLists();
Christian Heimesa156e092008-02-16 07:38:31 +0000789}
790
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000791/* This is the main function. Read this to understand how the
792 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000793static Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +0200794collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
795 int nofail)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 int i;
798 Py_ssize_t m = 0; /* # objects collected */
799 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
800 PyGC_Head *young; /* the generation we are examining */
801 PyGC_Head *old; /* next older generation */
802 PyGC_Head unreachable; /* non-problematic unreachable trash */
803 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
804 PyGC_Head *gc;
Victor Stinner7181dec2015-03-27 17:47:53 +0100805 _PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200806
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600807 struct gc_generation_stats *stats = &_PyRuntime.gc.generation_stats[generation];
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000808
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600809 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 PySys_WriteStderr("gc: collecting generation %d...\n",
811 generation);
812 PySys_WriteStderr("gc: objects in each generation:");
813 for (i = 0; i < NUM_GENERATIONS; i++)
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200814 PySys_FormatStderr(" %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 gc_list_size(GEN_HEAD(i)));
Victor Stinner7181dec2015-03-27 17:47:53 +0100816 t1 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PySys_WriteStderr("\n");
819 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000820
Łukasz Langaa785c872016-09-09 17:37:37 -0700821 if (PyDTrace_GC_START_ENABLED())
822 PyDTrace_GC_START(generation);
823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* update collection and allocation counters */
825 if (generation+1 < NUM_GENERATIONS)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600826 _PyRuntime.gc.generations[generation+1].count += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 for (i = 0; i <= generation; i++)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600828 _PyRuntime.gc.generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* merge younger generations with one we are currently collecting */
831 for (i = 0; i < generation; i++) {
832 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
833 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 /* handy references */
836 young = GEN_HEAD(generation);
837 if (generation < NUM_GENERATIONS-1)
838 old = GEN_HEAD(generation+1);
839 else
840 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* Using ob_refcnt and gc_refs, calculate which objects in the
843 * container set are reachable from outside the set (i.e., have a
844 * refcount greater than 0 when all the references within the
845 * set are taken into account).
846 */
847 update_refs(young);
848 subtract_refs(young);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 /* Leave everything reachable from outside young in young, and move
851 * everything else (in young) to unreachable.
852 * NOTE: This used to move the reachable objects into a reachable
853 * set instead. But most things usually turn out to be reachable,
854 * so it's more efficient to move the unreachable things.
855 */
856 gc_list_init(&unreachable);
857 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 /* Move reachable objects to next generation. */
860 if (young != old) {
861 if (generation == NUM_GENERATIONS - 2) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600862 _PyRuntime.gc.long_lived_pending += gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 }
864 gc_list_merge(young, old);
865 }
866 else {
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200867 /* We only untrack dicts in full collections, to avoid quadratic
868 dict build-up. See issue #14775. */
869 untrack_dicts(young);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 _PyRuntime.gc.long_lived_pending = 0;
871 _PyRuntime.gc.long_lived_total = gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* All objects in unreachable are trash, but objects reachable from
Antoine Pitrou796564c2013-07-30 19:59:21 +0200875 * legacy finalizers (e.g. tp_del) can't safely be deleted.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 */
877 gc_list_init(&finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200878 move_legacy_finalizers(&unreachable, &finalizers);
879 /* finalizers contains the unreachable objects with a legacy finalizer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 * unreachable objects reachable *from* those are also uncollectable,
881 * and we move those into the finalizers list too.
882 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200883 move_legacy_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 /* Collect statistics on collectable objects found and print
886 * debugging information.
887 */
888 for (gc = unreachable.gc.gc_next; gc != &unreachable;
889 gc = gc->gc.gc_next) {
890 m++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600891 if (_PyRuntime.gc.debug & DEBUG_COLLECTABLE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 debug_cycle("collectable", FROM_GC(gc));
893 }
894 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 /* Clear weakrefs and invoke callbacks as necessary. */
897 m += handle_weakrefs(&unreachable, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000898
Antoine Pitrou796564c2013-07-30 19:59:21 +0200899 /* Call tp_finalize on objects which have one. */
Tim Peters5fbc7b12014-05-08 17:42:19 -0500900 finalize_garbage(&unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200901
902 if (check_garbage(&unreachable)) {
903 revive_garbage(&unreachable);
904 gc_list_merge(&unreachable, old);
905 }
906 else {
907 /* Call tp_clear on objects in the unreachable set. This will cause
908 * the reference cycles to be broken. It may also cause some objects
909 * in finalizers to be freed.
910 */
911 delete_garbage(&unreachable, old);
912 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Collect statistics on uncollectable objects found and print
915 * debugging information. */
916 for (gc = finalizers.gc.gc_next;
917 gc != &finalizers;
918 gc = gc->gc.gc_next) {
919 n++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600920 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 debug_cycle("uncollectable", FROM_GC(gc));
922 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600923 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Victor Stinner7181dec2015-03-27 17:47:53 +0100924 _PyTime_t t2 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (m == 0 && n == 0)
927 PySys_WriteStderr("gc: done");
928 else
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200929 PySys_FormatStderr(
930 "gc: done, %zd unreachable, %zd uncollectable",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 n+m, n);
Victor Stinner7181dec2015-03-27 17:47:53 +0100932 PySys_WriteStderr(", %.4fs elapsed\n",
933 _PyTime_AsSecondsDouble(t2 - t1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Append instances in the uncollectable set to a Python
937 * reachable list of garbage. The programmer has to deal with
938 * this if they insist on creating this type of structure.
939 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200940 (void)handle_legacy_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Clear free list only during the collection of the highest
943 * generation */
944 if (generation == NUM_GENERATIONS-1) {
945 clear_freelists();
946 }
Christian Heimesa156e092008-02-16 07:38:31 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (PyErr_Occurred()) {
Antoine Pitroufef34e32013-05-19 01:11:58 +0200949 if (nofail) {
950 PyErr_Clear();
951 }
952 else {
953 if (gc_str == NULL)
954 gc_str = PyUnicode_FromString("garbage collection");
955 PyErr_WriteUnraisable(gc_str);
956 Py_FatalError("unexpected exception during garbage collection");
957 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000959
Antoine Pitroud4156c12012-10-30 22:43:19 +0100960 /* Update stats */
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000961 if (n_collected)
962 *n_collected = m;
963 if (n_uncollectable)
964 *n_uncollectable = n;
Antoine Pitroud4156c12012-10-30 22:43:19 +0100965 stats->collections++;
966 stats->collected += m;
967 stats->uncollectable += n;
Łukasz Langaa785c872016-09-09 17:37:37 -0700968
969 if (PyDTrace_GC_DONE_ENABLED())
970 PyDTrace_GC_DONE(n+m);
971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return n+m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000973}
974
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000975/* Invoke progress callbacks to notify clients that garbage collection
976 * is starting or stopping
977 */
978static void
979invoke_gc_callback(const char *phase, int generation,
980 Py_ssize_t collected, Py_ssize_t uncollectable)
981{
982 Py_ssize_t i;
983 PyObject *info = NULL;
984
985 /* we may get called very early */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600986 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000987 return;
988 /* The local variable cannot be rebound, check it for sanity */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600989 assert(_PyRuntime.gc.callbacks != NULL && PyList_CheckExact(_PyRuntime.gc.callbacks));
990 if (PyList_GET_SIZE(_PyRuntime.gc.callbacks) != 0) {
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000991 info = Py_BuildValue("{sisnsn}",
992 "generation", generation,
993 "collected", collected,
994 "uncollectable", uncollectable);
995 if (info == NULL) {
996 PyErr_WriteUnraisable(NULL);
997 return;
998 }
999 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001000 for (i=0; i<PyList_GET_SIZE(_PyRuntime.gc.callbacks); i++) {
1001 PyObject *r, *cb = PyList_GET_ITEM(_PyRuntime.gc.callbacks, i);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001002 Py_INCREF(cb); /* make sure cb doesn't go away */
1003 r = PyObject_CallFunction(cb, "sO", phase, info);
1004 Py_XDECREF(r);
1005 if (r == NULL)
1006 PyErr_WriteUnraisable(cb);
1007 Py_DECREF(cb);
1008 }
1009 Py_XDECREF(info);
1010}
1011
1012/* Perform garbage collection of a generation and invoke
1013 * progress callbacks.
1014 */
1015static Py_ssize_t
1016collect_with_callback(int generation)
1017{
1018 Py_ssize_t result, collected, uncollectable;
1019 invoke_gc_callback("start", generation, 0, 0);
Antoine Pitroufef34e32013-05-19 01:11:58 +02001020 result = collect(generation, &collected, &uncollectable, 0);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001021 invoke_gc_callback("stop", generation, collected, uncollectable);
1022 return result;
1023}
1024
Neal Norwitz7b216c52006-03-04 20:01:53 +00001025static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001026collect_generations(void)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 int i;
1029 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* Find the oldest generation (highest numbered) where the count
1032 * exceeds the threshold. Objects in the that generation and
1033 * generations younger than it will be collected. */
1034 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001035 if (_PyRuntime.gc.generations[i].count > _PyRuntime.gc.generations[i].threshold) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Avoid quadratic performance degradation in number
1037 of tracked objects. See comments at the beginning
1038 of this file, and issue #4074.
1039 */
1040 if (i == NUM_GENERATIONS - 1
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001041 && _PyRuntime.gc.long_lived_pending < _PyRuntime.gc.long_lived_total / 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 continue;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001043 n = collect_with_callback(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 break;
1045 }
1046 }
1047 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001048}
1049
Serhiy Storchaka93260282017-02-04 11:19:59 +02001050#include "clinic/gcmodule.c.h"
1051
1052/*[clinic input]
1053gc.enable
1054
1055Enable automatic garbage collection.
1056[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001057
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001058static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001059gc_enable_impl(PyObject *module)
1060/*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001061{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001062 _PyRuntime.gc.enabled = 1;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001063 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001064}
1065
Serhiy Storchaka93260282017-02-04 11:19:59 +02001066/*[clinic input]
1067gc.disable
1068
1069Disable automatic garbage collection.
1070[clinic start generated code]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001071
1072static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001073gc_disable_impl(PyObject *module)
1074/*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a14e800d83b]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001075{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001076 _PyRuntime.gc.enabled = 0;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001077 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001078}
1079
Serhiy Storchaka93260282017-02-04 11:19:59 +02001080/*[clinic input]
1081gc.isenabled -> bool
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001082
Serhiy Storchaka93260282017-02-04 11:19:59 +02001083Returns true if automatic garbage collection is enabled.
1084[clinic start generated code]*/
1085
1086static int
1087gc_isenabled_impl(PyObject *module)
1088/*[clinic end generated code: output=1874298331c49130 input=30005e0422373b31]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001089{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001090 return _PyRuntime.gc.enabled;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001091}
1092
Serhiy Storchaka93260282017-02-04 11:19:59 +02001093/*[clinic input]
1094gc.collect -> Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001095
Serhiy Storchaka93260282017-02-04 11:19:59 +02001096 generation: int(c_default="NUM_GENERATIONS - 1") = 2
1097
1098Run the garbage collector.
1099
1100With no arguments, run a full collection. The optional argument
1101may be an integer specifying which generation to collect. A ValueError
1102is raised if the generation number is invalid.
1103
1104The number of unreachable objects is returned.
1105[clinic start generated code]*/
1106
1107static Py_ssize_t
1108gc_collect_impl(PyObject *module, int generation)
1109/*[clinic end generated code: output=b697e633043233c7 input=40720128b682d879]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001112
Serhiy Storchaka93260282017-02-04 11:19:59 +02001113 if (generation < 0 || generation >= NUM_GENERATIONS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyErr_SetString(PyExc_ValueError, "invalid generation");
Serhiy Storchaka93260282017-02-04 11:19:59 +02001115 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 }
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001117
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001118 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 n = 0; /* already collecting, don't do anything */
1120 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001121 _PyRuntime.gc.collecting = 1;
Serhiy Storchaka93260282017-02-04 11:19:59 +02001122 n = collect_with_callback(generation);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001123 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001125
Serhiy Storchaka93260282017-02-04 11:19:59 +02001126 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001127}
1128
Serhiy Storchaka93260282017-02-04 11:19:59 +02001129/*[clinic input]
1130gc.set_debug
1131
1132 flags: int
1133 An integer that can have the following bits turned on:
1134 DEBUG_STATS - Print statistics during collection.
1135 DEBUG_COLLECTABLE - Print collectable objects found.
1136 DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
1137 found.
1138 DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
1139 DEBUG_LEAK - Debug leaking programs (everything but STATS).
1140 /
1141
1142Set the garbage collection debugging flags.
1143
1144Debugging information is written to sys.stderr.
1145[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001146
1147static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001148gc_set_debug_impl(PyObject *module, int flags)
1149/*[clinic end generated code: output=7c8366575486b228 input=5e5ce15e84fbed15]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001150{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001151 _PyRuntime.gc.debug = flags;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001152
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001153 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001154}
1155
Serhiy Storchaka93260282017-02-04 11:19:59 +02001156/*[clinic input]
1157gc.get_debug -> int
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001158
Serhiy Storchaka93260282017-02-04 11:19:59 +02001159Get the garbage collection debugging flags.
1160[clinic start generated code]*/
1161
1162static int
1163gc_get_debug_impl(PyObject *module)
1164/*[clinic end generated code: output=91242f3506cd1e50 input=91a101e1c3b98366]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001165{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001166 return _PyRuntime.gc.debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001167}
1168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001169PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001170"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001171"\n"
1172"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001173"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001174
1175static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001176gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 int i;
1179 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001180 &_PyRuntime.gc.generations[0].threshold,
1181 &_PyRuntime.gc.generations[1].threshold,
1182 &_PyRuntime.gc.generations[2].threshold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return NULL;
1184 for (i = 2; i < NUM_GENERATIONS; i++) {
1185 /* generations higher than 2 get the same threshold */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001186 _PyRuntime.gc.generations[i].threshold = _PyRuntime.gc.generations[2].threshold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001188
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001189 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001190}
1191
Serhiy Storchaka93260282017-02-04 11:19:59 +02001192/*[clinic input]
1193gc.get_threshold
1194
1195Return the current collection thresholds.
1196[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001197
1198static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001199gc_get_threshold_impl(PyObject *module)
1200/*[clinic end generated code: output=7902bc9f41ecbbd8 input=286d79918034d6e6]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001203 _PyRuntime.gc.generations[0].threshold,
1204 _PyRuntime.gc.generations[1].threshold,
1205 _PyRuntime.gc.generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001206}
1207
Serhiy Storchaka93260282017-02-04 11:19:59 +02001208/*[clinic input]
1209gc.get_count
1210
1211Return a three-tuple of the current collection counts.
1212[clinic start generated code]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001213
1214static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001215gc_get_count_impl(PyObject *module)
1216/*[clinic end generated code: output=354012e67b16398f input=a392794a08251751]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001219 _PyRuntime.gc.generations[0].count,
1220 _PyRuntime.gc.generations[1].count,
1221 _PyRuntime.gc.generations[2].count);
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001222}
1223
Neil Schemenauer48c70342001-08-09 15:38:31 +00001224static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001225referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 Py_ssize_t i;
1228 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1229 if (PyTuple_GET_ITEM(objs, i) == obj)
1230 return 1;
1231 return 0;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001232}
1233
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001234static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001235gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyGC_Head *gc;
1238 PyObject *obj;
1239 traverseproc traverse;
1240 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
1241 obj = FROM_GC(gc);
1242 traverse = Py_TYPE(obj)->tp_traverse;
1243 if (obj == objs || obj == resultlist)
1244 continue;
1245 if (traverse(obj, (visitproc)referrersvisit, objs)) {
1246 if (PyList_Append(resultlist, obj) < 0)
1247 return 0; /* error */
1248 }
1249 }
1250 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001251}
1252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001253PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001254"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001255Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001256
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001257static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001258gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 int i;
1261 PyObject *result = PyList_New(0);
1262 if (!result) return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 for (i = 0; i < NUM_GENERATIONS; i++) {
1265 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1266 Py_DECREF(result);
1267 return NULL;
1268 }
1269 }
1270 return result;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001271}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001272
Tim Peters0f81ab62003-04-08 16:39:48 +00001273/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001274static int
Tim Peters730f5532003-04-08 17:17:17 +00001275referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001278}
1279
Tim Peters730f5532003-04-08 17:17:17 +00001280PyDoc_STRVAR(gc_get_referents__doc__,
1281"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001282Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001283
1284static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001285gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 Py_ssize_t i;
1288 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 if (result == NULL)
1291 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
1294 traverseproc traverse;
1295 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (! PyObject_IS_GC(obj))
1298 continue;
1299 traverse = Py_TYPE(obj)->tp_traverse;
1300 if (! traverse)
1301 continue;
1302 if (traverse(obj, (visitproc)referentsvisit, result)) {
1303 Py_DECREF(result);
1304 return NULL;
1305 }
1306 }
1307 return result;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001308}
1309
Serhiy Storchaka93260282017-02-04 11:19:59 +02001310/*[clinic input]
1311gc.get_objects
1312
1313Return a list of objects tracked by the collector (excluding the list returned).
1314[clinic start generated code]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001315
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001316static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001317gc_get_objects_impl(PyObject *module)
1318/*[clinic end generated code: output=fcb95d2e23e1f750 input=9439fe8170bf35d8]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 int i;
1321 PyObject* result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 result = PyList_New(0);
1324 if (result == NULL)
1325 return NULL;
1326 for (i = 0; i < NUM_GENERATIONS; i++) {
1327 if (append_objects(result, GEN_HEAD(i))) {
1328 Py_DECREF(result);
1329 return NULL;
1330 }
1331 }
1332 return result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001333}
1334
Serhiy Storchaka93260282017-02-04 11:19:59 +02001335/*[clinic input]
1336gc.get_stats
1337
1338Return a list of dictionaries containing per-generation statistics.
1339[clinic start generated code]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001340
1341static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001342gc_get_stats_impl(PyObject *module)
1343/*[clinic end generated code: output=a8ab1d8a5d26f3ab input=1ef4ed9d17b1a470]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001344{
1345 int i;
1346 PyObject *result;
1347 struct gc_generation_stats stats[NUM_GENERATIONS], *st;
1348
1349 /* To get consistent values despite allocations while constructing
1350 the result list, we use a snapshot of the running stats. */
1351 for (i = 0; i < NUM_GENERATIONS; i++) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001352 stats[i] = _PyRuntime.gc.generation_stats[i];
Antoine Pitroud4156c12012-10-30 22:43:19 +01001353 }
1354
1355 result = PyList_New(0);
1356 if (result == NULL)
1357 return NULL;
1358
1359 for (i = 0; i < NUM_GENERATIONS; i++) {
1360 PyObject *dict;
1361 st = &stats[i];
1362 dict = Py_BuildValue("{snsnsn}",
1363 "collections", st->collections,
1364 "collected", st->collected,
1365 "uncollectable", st->uncollectable
1366 );
1367 if (dict == NULL)
1368 goto error;
1369 if (PyList_Append(result, dict)) {
1370 Py_DECREF(dict);
1371 goto error;
1372 }
1373 Py_DECREF(dict);
1374 }
1375 return result;
1376
1377error:
1378 Py_XDECREF(result);
1379 return NULL;
1380}
1381
1382
Serhiy Storchaka93260282017-02-04 11:19:59 +02001383/*[clinic input]
1384gc.is_tracked
1385
1386 obj: object
1387 /
1388
1389Returns true if the object is tracked by the garbage collector.
1390
1391Simple atomic objects will return false.
1392[clinic start generated code]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001393
1394static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001395gc_is_tracked(PyObject *module, PyObject *obj)
1396/*[clinic end generated code: output=14f0103423b28e31 input=d83057f170ea2723]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyObject *result;
1399
1400 if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
1401 result = Py_True;
1402 else
1403 result = Py_False;
1404 Py_INCREF(result);
1405 return result;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001406}
1407
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001408
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001409PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001410"This module provides access to the garbage collector for reference cycles.\n"
1411"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001412"enable() -- Enable automatic garbage collection.\n"
1413"disable() -- Disable automatic garbage collection.\n"
1414"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001415"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001416"get_count() -- Return the current collection counts.\n"
R David Murray0e814632013-12-26 15:11:28 -05001417"get_stats() -- Return list of dictionaries containing per-generation stats.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001418"set_debug() -- Set debugging flags.\n"
1419"get_debug() -- Get debugging flags.\n"
1420"set_threshold() -- Set the collection thresholds.\n"
1421"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001422"get_objects() -- Return a list of all objects tracked by the collector.\n"
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001423"is_tracked() -- Returns true if a given object is tracked.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001424"get_referrers() -- Return the list of objects that refer to an object.\n"
Tim Peters730f5532003-04-08 17:17:17 +00001425"get_referents() -- Return the list of objects that an object refers to.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001426
1427static PyMethodDef GcMethods[] = {
Serhiy Storchaka93260282017-02-04 11:19:59 +02001428 GC_ENABLE_METHODDEF
1429 GC_DISABLE_METHODDEF
1430 GC_ISENABLED_METHODDEF
1431 GC_SET_DEBUG_METHODDEF
1432 GC_GET_DEBUG_METHODDEF
1433 GC_GET_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Serhiy Storchaka93260282017-02-04 11:19:59 +02001435 GC_GET_THRESHOLD_METHODDEF
1436 GC_COLLECT_METHODDEF
1437 GC_GET_OBJECTS_METHODDEF
1438 GC_GET_STATS_METHODDEF
1439 GC_IS_TRACKED_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 {"get_referrers", gc_get_referrers, METH_VARARGS,
1441 gc_get_referrers__doc__},
1442 {"get_referents", gc_get_referents, METH_VARARGS,
1443 gc_get_referents__doc__},
1444 {NULL, NULL} /* Sentinel */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001445};
1446
Martin v. Löwis1a214512008-06-11 05:26:20 +00001447static struct PyModuleDef gcmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyModuleDef_HEAD_INIT,
Antoine Pitrou696e0352010-08-08 22:18:46 +00001449 "gc", /* m_name */
1450 gc__doc__, /* m_doc */
1451 -1, /* m_size */
1452 GcMethods, /* m_methods */
1453 NULL, /* m_reload */
1454 NULL, /* m_traverse */
1455 NULL, /* m_clear */
1456 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001457};
1458
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001459PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001460PyInit_gc(void)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 m = PyModule_Create(&gcmodule);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 if (m == NULL)
1467 return NULL;
Tim Peters11558872003-04-06 23:30:52 +00001468
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001469 if (_PyRuntime.gc.garbage == NULL) {
1470 _PyRuntime.gc.garbage = PyList_New(0);
1471 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 return NULL;
1473 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001474 Py_INCREF(_PyRuntime.gc.garbage);
1475 if (PyModule_AddObject(m, "garbage", _PyRuntime.gc.garbage) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001477
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001478 if (_PyRuntime.gc.callbacks == NULL) {
1479 _PyRuntime.gc.callbacks = PyList_New(0);
1480 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001481 return NULL;
1482 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001483 Py_INCREF(_PyRuntime.gc.callbacks);
1484 if (PyModule_AddObject(m, "callbacks", _PyRuntime.gc.callbacks) < 0)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001485 return NULL;
1486
Martin v. Löwis1a214512008-06-11 05:26:20 +00001487#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 ADD_INT(DEBUG_STATS);
1489 ADD_INT(DEBUG_COLLECTABLE);
1490 ADD_INT(DEBUG_UNCOLLECTABLE);
1491 ADD_INT(DEBUG_SAVEALL);
1492 ADD_INT(DEBUG_LEAK);
Tim Peters11558872003-04-06 23:30:52 +00001493#undef ADD_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001495}
1496
Guido van Rossume13ddc92003-04-17 17:29:22 +00001497/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001498Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001499PyGC_Collect(void)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001502
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001503 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 n = 0; /* already collecting, don't do anything */
1505 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001506 _PyRuntime.gc.collecting = 1;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001507 n = collect_with_callback(NUM_GENERATIONS - 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001508 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 }
Guido van Rossume13ddc92003-04-17 17:29:22 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 return n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001512}
1513
Antoine Pitroufef34e32013-05-19 01:11:58 +02001514Py_ssize_t
Łukasz Langafef7e942016-09-09 21:47:46 -07001515_PyGC_CollectIfEnabled(void)
1516{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001517 if (!_PyRuntime.gc.enabled)
Łukasz Langafef7e942016-09-09 21:47:46 -07001518 return 0;
1519
1520 return PyGC_Collect();
1521}
1522
1523Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +02001524_PyGC_CollectNoFail(void)
1525{
1526 Py_ssize_t n;
1527
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001528 /* Ideally, this function is only called on interpreter shutdown,
1529 and therefore not recursively. Unfortunately, when there are daemon
1530 threads, a daemon thread can start a cyclic garbage collection
1531 during interpreter shutdown (and then never finish it).
1532 See http://bugs.python.org/issue8713#msg195178 for an example.
1533 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001534 if (_PyRuntime.gc.collecting)
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001535 n = 0;
1536 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001537 _PyRuntime.gc.collecting = 1;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001538 n = collect(NUM_GENERATIONS - 1, NULL, NULL, 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001539 _PyRuntime.gc.collecting = 0;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001540 }
Antoine Pitroufef34e32013-05-19 01:11:58 +02001541 return n;
1542}
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001543
Antoine Pitrou696e0352010-08-08 22:18:46 +00001544void
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001545_PyGC_DumpShutdownStats(void)
Antoine Pitrou696e0352010-08-08 22:18:46 +00001546{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001547 if (!(_PyRuntime.gc.debug & DEBUG_SAVEALL)
1548 && _PyRuntime.gc.garbage != NULL && PyList_GET_SIZE(_PyRuntime.gc.garbage) > 0) {
Georg Brandl08be72d2010-10-24 15:11:22 +00001549 char *message;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001550 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitroub5d82042010-11-05 00:05:25 +00001551 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001552 "shutdown";
1553 else
Antoine Pitroub5d82042010-11-05 00:05:25 +00001554 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001555 "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001556 /* PyErr_WarnFormat does too many things and we are at shutdown,
1557 the warnings module's dependencies (e.g. linecache) may be gone
1558 already. */
1559 if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1560 "gc", NULL, message,
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001561 PyList_GET_SIZE(_PyRuntime.gc.garbage)))
Georg Brandl08be72d2010-10-24 15:11:22 +00001562 PyErr_WriteUnraisable(NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001563 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE) {
Antoine Pitrou696e0352010-08-08 22:18:46 +00001564 PyObject *repr = NULL, *bytes = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001565 repr = PyObject_Repr(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001566 if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001567 PyErr_WriteUnraisable(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001568 else {
1569 PySys_WriteStderr(
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001570 " %s\n",
Antoine Pitrou696e0352010-08-08 22:18:46 +00001571 PyBytes_AS_STRING(bytes)
1572 );
1573 }
1574 Py_XDECREF(repr);
1575 Py_XDECREF(bytes);
1576 }
Antoine Pitrou696e0352010-08-08 22:18:46 +00001577 }
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001578}
1579
1580void
1581_PyGC_Fini(void)
1582{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001583 Py_CLEAR(_PyRuntime.gc.callbacks);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001584}
1585
Neil Schemenauer43411b52001-08-30 00:05:51 +00001586/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001587void
1588_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 _PyObject_Dump(FROM_GC(g));
Neil Schemenauer43411b52001-08-30 00:05:51 +00001591}
1592
Neil Schemenauer43411b52001-08-30 00:05:51 +00001593/* extension modules might be compiled with GC support so these
1594 functions must always be available */
1595
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001596#undef PyObject_GC_Track
1597#undef PyObject_GC_UnTrack
1598#undef PyObject_GC_Del
1599#undef _PyObject_GC_Malloc
1600
Neil Schemenauer43411b52001-08-30 00:05:51 +00001601void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001602PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 _PyObject_GC_TRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001605}
1606
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001607void
1608PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001609{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1611 * call PyObject_GC_UnTrack twice on an object.
1612 */
1613 if (IS_TRACKED(op))
1614 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001615}
1616
Victor Stinnerdb067af2014-05-02 22:31:14 +02001617static PyObject *
1618_PyObject_GC_Alloc(int use_calloc, size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 PyObject *op;
1621 PyGC_Head *g;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001622 size_t size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1624 return PyErr_NoMemory();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001625 size = sizeof(PyGC_Head) + basicsize;
1626 if (use_calloc)
1627 g = (PyGC_Head *)PyObject_Calloc(1, size);
1628 else
1629 g = (PyGC_Head *)PyObject_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 if (g == NULL)
1631 return PyErr_NoMemory();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001632 g->gc.gc_refs = 0;
1633 _PyGCHead_SET_REFS(g, GC_UNTRACKED);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001634 _PyRuntime.gc.generations[0].count++; /* number of allocated GC objects */
1635 if (_PyRuntime.gc.generations[0].count > _PyRuntime.gc.generations[0].threshold &&
1636 _PyRuntime.gc.enabled &&
1637 _PyRuntime.gc.generations[0].threshold &&
1638 !_PyRuntime.gc.collecting &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 !PyErr_Occurred()) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001640 _PyRuntime.gc.collecting = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 collect_generations();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001642 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 }
1644 op = FROM_GC(g);
1645 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001646}
1647
1648PyObject *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001649_PyObject_GC_Malloc(size_t basicsize)
1650{
1651 return _PyObject_GC_Alloc(0, basicsize);
1652}
1653
1654PyObject *
1655_PyObject_GC_Calloc(size_t basicsize)
1656{
1657 return _PyObject_GC_Alloc(1, basicsize);
1658}
1659
1660PyObject *
Neil Schemenauer43411b52001-08-30 00:05:51 +00001661_PyObject_GC_New(PyTypeObject *tp)
1662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
1664 if (op != NULL)
1665 op = PyObject_INIT(op, tp);
1666 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001667}
1668
1669PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001670_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001671{
Victor Stinner5d1866c2013-07-08 22:17:52 +02001672 size_t size;
1673 PyVarObject *op;
1674
1675 if (nitems < 0) {
1676 PyErr_BadInternalCall();
1677 return NULL;
1678 }
1679 size = _PyObject_VAR_SIZE(tp, nitems);
1680 op = (PyVarObject *) _PyObject_GC_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (op != NULL)
1682 op = PyObject_INIT_VAR(op, tp, nitems);
1683 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001684}
1685
1686PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001687_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
1690 PyGC_Head *g = AS_GC(op);
1691 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1692 return (PyVarObject *)PyErr_NoMemory();
1693 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
1694 if (g == NULL)
1695 return (PyVarObject *)PyErr_NoMemory();
1696 op = (PyVarObject *) FROM_GC(g);
1697 Py_SIZE(op) = nitems;
1698 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001699}
1700
1701void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001702PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PyGC_Head *g = AS_GC(op);
1705 if (IS_TRACKED(op))
1706 gc_list_remove(g);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001707 if (_PyRuntime.gc.generations[0].count > 0) {
1708 _PyRuntime.gc.generations[0].count--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 }
1710 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001711}