blob: 121eb46012cdccf6eae1754b4b785f27c4a9e3fd [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);
brainfvckc75edab2017-10-16 12:49:41 -070074 struct gc_generation permanent_generation = {
75 {{&state->permanent_generation.head, &state->permanent_generation.head, 0}}, 0, 0
76 };
77 state->permanent_generation = permanent_generation;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078}
Antoine Pitroud4156c12012-10-30 22:43:19 +010079
Tim Peters6fc13d92002-07-02 18:12:35 +000080/*--------------------------------------------------------------------------
81gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +000082
Tim Peters6fc13d92002-07-02 18:12:35 +000083Between collections, every gc'ed object has one of two gc_refs values:
84
85GC_UNTRACKED
86 The initial state; objects returned by PyObject_GC_Malloc are in this
87 state. The object doesn't live in any generation list, and its
88 tp_traverse slot must not be called.
89
90GC_REACHABLE
91 The object lives in some generation list, and its tp_traverse is safe to
92 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
93 is called.
94
95During a collection, gc_refs can temporarily take on other states:
96
97>= 0
98 At the start of a collection, update_refs() copies the true refcount
99 to gc_refs, for each object in the generation being collected.
100 subtract_refs() then adjusts gc_refs so that it equals the number of
101 times an object is referenced directly from outside the generation
102 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +0000103 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000104
105GC_TENTATIVELY_UNREACHABLE
106 move_unreachable() then moves objects not reachable (whether directly or
107 indirectly) from outside the generation into an "unreachable" set.
108 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
109 again. Objects that are found to be unreachable have gc_refs set to
110 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
111 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
112 transition back to GC_REACHABLE.
113
114 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
115 for collection. If it's decided not to collect such an object (e.g.,
116 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
117----------------------------------------------------------------------------
118*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
120#define GC_REACHABLE _PyGC_REFS_REACHABLE
121#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000122
Antoine Pitrou796564c2013-07-30 19:59:21 +0200123#define IS_TRACKED(o) (_PyGC_REFS(o) != GC_UNTRACKED)
124#define IS_REACHABLE(o) (_PyGC_REFS(o) == GC_REACHABLE)
Tim Peters19b74c72002-07-01 03:52:19 +0000125#define IS_TENTATIVELY_UNREACHABLE(o) ( \
Antoine Pitrou796564c2013-07-30 19:59:21 +0200126 _PyGC_REFS(o) == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000127
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000128/*** list functions ***/
129
130static void
131gc_list_init(PyGC_Head *list)
132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 list->gc.gc_prev = list;
134 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000135}
136
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000137static int
138gc_list_is_empty(PyGC_Head *list)
139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return (list->gc.gc_next == list);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000141}
142
Tim Peterse2d59182004-11-01 01:39:08 +0000143#if 0
144/* This became unused after gc_list_move() was introduced. */
145/* Append `node` to `list`. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000146static void
147gc_list_append(PyGC_Head *node, PyGC_Head *list)
148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 node->gc.gc_next = list;
150 node->gc.gc_prev = list->gc.gc_prev;
151 node->gc.gc_prev->gc.gc_next = node;
152 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000153}
Tim Peterse2d59182004-11-01 01:39:08 +0000154#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000155
Tim Peterse2d59182004-11-01 01:39:08 +0000156/* Remove `node` from the gc list it's currently in. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000157static void
158gc_list_remove(PyGC_Head *node)
159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
161 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
162 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000163}
164
Tim Peterse2d59182004-11-01 01:39:08 +0000165/* Move `node` from the gc list it's currently in (which is not explicitly
166 * named here) to the end of `list`. This is semantically the same as
167 * gc_list_remove(node) followed by gc_list_append(node, list).
168 */
169static void
170gc_list_move(PyGC_Head *node, PyGC_Head *list)
171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 PyGC_Head *new_prev;
173 PyGC_Head *current_prev = node->gc.gc_prev;
174 PyGC_Head *current_next = node->gc.gc_next;
175 /* Unlink from current list. */
176 current_prev->gc.gc_next = current_next;
177 current_next->gc.gc_prev = current_prev;
178 /* Relink at end of new list. */
179 new_prev = node->gc.gc_prev = list->gc.gc_prev;
180 new_prev->gc.gc_next = list->gc.gc_prev = node;
181 node->gc.gc_next = list;
Tim Peterse2d59182004-11-01 01:39:08 +0000182}
183
184/* append list `from` onto list `to`; `from` becomes an empty list */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000185static void
186gc_list_merge(PyGC_Head *from, PyGC_Head *to)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyGC_Head *tail;
189 assert(from != to);
190 if (!gc_list_is_empty(from)) {
191 tail = to->gc.gc_prev;
192 tail->gc.gc_next = from->gc.gc_next;
193 tail->gc.gc_next->gc.gc_prev = tail;
194 to->gc.gc_prev = from->gc.gc_prev;
195 to->gc.gc_prev->gc.gc_next = to;
196 }
197 gc_list_init(from);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000198}
199
Neal Norwitz7b216c52006-03-04 20:01:53 +0000200static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000201gc_list_size(PyGC_Head *list)
202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyGC_Head *gc;
204 Py_ssize_t n = 0;
205 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
206 n++;
207 }
208 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000209}
210
Tim Peters259272b2003-04-06 19:41:39 +0000211/* Append objects in a GC list to a Python list.
212 * Return 0 if all OK, < 0 if error (out of memory for list).
213 */
214static int
215append_objects(PyObject *py_list, PyGC_Head *gc_list)
216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyGC_Head *gc;
218 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
219 PyObject *op = FROM_GC(gc);
220 if (op != py_list) {
221 if (PyList_Append(py_list, op)) {
222 return -1; /* exception */
223 }
224 }
225 }
226 return 0;
Tim Peters259272b2003-04-06 19:41:39 +0000227}
228
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000229/*** end of list stuff ***/
230
231
Tim Peters19b74c72002-07-01 03:52:19 +0000232/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
233 * in containers, and is GC_REACHABLE for all tracked gc objects not in
234 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000235 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000236static void
237update_refs(PyGC_Head *containers)
238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyGC_Head *gc = containers->gc.gc_next;
240 for (; gc != containers; gc = gc->gc.gc_next) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200241 assert(_PyGCHead_REFS(gc) == GC_REACHABLE);
242 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 /* Python's cyclic gc should never see an incoming refcount
244 * of 0: if something decref'ed to 0, it should have been
245 * deallocated immediately at that time.
246 * Possible cause (if the assert triggers): a tp_dealloc
247 * routine left a gc-aware object tracked during its teardown
248 * phase, and did something-- or allowed something to happen --
249 * that called back into Python. gc can trigger then, and may
250 * see the still-tracked dying object. Before this assert
251 * was added, such mistakes went on to allow gc to try to
252 * delete the object again. In a debug build, that caused
253 * a mysterious segfault, when _Py_ForgetReference tried
254 * to remove the object from the doubly-linked list of all
255 * objects a second time. In a release build, an actual
256 * double deallocation occurred, which leads to corruption
257 * of the allocator's internal bookkeeping pointers. That's
258 * so serious that maybe this should be a release-build
259 * check instead of an assert?
260 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200261 assert(_PyGCHead_REFS(gc) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000263}
264
Tim Peters19b74c72002-07-01 03:52:19 +0000265/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000266static int
267visit_decref(PyObject *op, void *data)
268{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 assert(op != NULL);
270 if (PyObject_IS_GC(op)) {
271 PyGC_Head *gc = AS_GC(op);
272 /* We're only interested in gc_refs for objects in the
273 * generation being collected, which can be recognized
274 * because only they have positive gc_refs.
275 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200276 assert(_PyGCHead_REFS(gc) != 0); /* else refcount was too small */
277 if (_PyGCHead_REFS(gc) > 0)
278 _PyGCHead_DECREF(gc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 }
280 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000281}
282
Tim Peters19b74c72002-07-01 03:52:19 +0000283/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
284 * for all objects in containers, and is GC_REACHABLE for all tracked gc
285 * objects not in containers. The ones with gc_refs > 0 are directly
286 * reachable from outside containers, and so can't be collected.
287 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000288static void
289subtract_refs(PyGC_Head *containers)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 traverseproc traverse;
292 PyGC_Head *gc = containers->gc.gc_next;
293 for (; gc != containers; gc=gc->gc.gc_next) {
294 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
295 (void) traverse(FROM_GC(gc),
296 (visitproc)visit_decref,
297 NULL);
298 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000299}
300
Tim Peters19b74c72002-07-01 03:52:19 +0000301/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000302static int
Tim Peters19b74c72002-07-01 03:52:19 +0000303visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 if (PyObject_IS_GC(op)) {
306 PyGC_Head *gc = AS_GC(op);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200307 const Py_ssize_t gc_refs = _PyGCHead_REFS(gc);
Tim Peters19b74c72002-07-01 03:52:19 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 if (gc_refs == 0) {
310 /* This is in move_unreachable's 'young' list, but
311 * the traversal hasn't yet gotten to it. All
312 * we need to do is tell move_unreachable that it's
313 * reachable.
314 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200315 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 }
317 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
318 /* This had gc_refs = 0 when move_unreachable got
319 * to it, but turns out it's reachable after all.
320 * Move it back to move_unreachable's 'young' list,
321 * and move_unreachable will eventually get to it
322 * again.
323 */
324 gc_list_move(gc, reachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200325 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 }
327 /* Else there's nothing to do.
328 * If gc_refs > 0, it must be in move_unreachable's 'young'
329 * list, and move_unreachable will eventually get to it.
330 * If gc_refs == GC_REACHABLE, it's either in some other
331 * generation so we don't care about it, or move_unreachable
332 * already dealt with it.
333 * If gc_refs == GC_UNTRACKED, it must be ignored.
334 */
335 else {
336 assert(gc_refs > 0
337 || gc_refs == GC_REACHABLE
338 || gc_refs == GC_UNTRACKED);
339 }
340 }
341 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000342}
343
Tim Peters19b74c72002-07-01 03:52:19 +0000344/* Move the unreachable objects from young to unreachable. After this,
345 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
346 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
347 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
348 * All objects in young after this are directly or indirectly reachable
349 * from outside the original young; and all objects in unreachable are
350 * not.
Tim Peters88396172002-06-30 17:56:40 +0000351 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000352static void
Tim Peters19b74c72002-07-01 03:52:19 +0000353move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 PyGC_Head *gc = young->gc.gc_next;
Tim Peters19b74c72002-07-01 03:52:19 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 /* Invariants: all objects "to the left" of us in young have gc_refs
358 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
359 * from outside the young list as it was at entry. All other objects
360 * from the original young "to the left" of us are in unreachable now,
361 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
362 * left of us in 'young' now have been scanned, and no objects here
363 * or to the right have been scanned yet.
364 */
Tim Peters19b74c72002-07-01 03:52:19 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 while (gc != young) {
367 PyGC_Head *next;
Tim Peters19b74c72002-07-01 03:52:19 +0000368
Antoine Pitrou796564c2013-07-30 19:59:21 +0200369 if (_PyGCHead_REFS(gc)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 /* gc is definitely reachable from outside the
371 * original 'young'. Mark it as such, and traverse
372 * its pointers to find any other objects that may
373 * be directly reachable from it. Note that the
374 * call to tp_traverse may append objects to young,
375 * so we have to wait until it returns to determine
376 * the next object to visit.
377 */
378 PyObject *op = FROM_GC(gc);
379 traverseproc traverse = Py_TYPE(op)->tp_traverse;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200380 assert(_PyGCHead_REFS(gc) > 0);
381 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 (void) traverse(op,
383 (visitproc)visit_reachable,
384 (void *)young);
385 next = gc->gc.gc_next;
386 if (PyTuple_CheckExact(op)) {
387 _PyTuple_MaybeUntrack(op);
388 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 }
390 else {
391 /* This *may* be unreachable. To make progress,
392 * assume it is. gc isn't directly reachable from
393 * any object we've already traversed, but may be
394 * reachable from an object we haven't gotten to yet.
395 * visit_reachable will eventually move gc back into
396 * young if that's so, and we'll see it again.
397 */
398 next = gc->gc.gc_next;
399 gc_list_move(gc, unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200400 _PyGCHead_SET_REFS(gc, GC_TENTATIVELY_UNREACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 }
402 gc = next;
403 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000404}
405
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200406/* Try to untrack all currently tracked dictionaries */
407static void
408untrack_dicts(PyGC_Head *head)
409{
410 PyGC_Head *next, *gc = head->gc.gc_next;
411 while (gc != head) {
412 PyObject *op = FROM_GC(gc);
413 next = gc->gc.gc_next;
414 if (PyDict_CheckExact(op))
415 _PyDict_MaybeUntrack(op);
416 gc = next;
417 }
418}
419
Antoine Pitrou796564c2013-07-30 19:59:21 +0200420/* Return true if object has a pre-PEP 442 finalization method. */
Neil Schemenauera765c122001-11-01 17:35:23 +0000421static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200422has_legacy_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000423{
Antoine Pitrou796564c2013-07-30 19:59:21 +0200424 return op->ob_type->tp_del != NULL;
Neil Schemenauera765c122001-11-01 17:35:23 +0000425}
426
Antoine Pitrou796564c2013-07-30 19:59:21 +0200427/* Move the objects in unreachable with tp_del slots into `finalizers`.
Tim Petersead8b7a2004-10-30 23:09:22 +0000428 * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the
429 * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000430 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000431static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200432move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 PyGC_Head *gc;
435 PyGC_Head *next;
Tim Petersf6b80452003-04-07 19:21:15 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 /* March over unreachable. Move objects with finalizers into
438 * `finalizers`.
439 */
440 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
441 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 assert(IS_TENTATIVELY_UNREACHABLE(op));
444 next = gc->gc.gc_next;
Tim Petersf6ae7a42003-04-05 18:40:50 +0000445
Antoine Pitrou796564c2013-07-30 19:59:21 +0200446 if (has_legacy_finalizer(op)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 gc_list_move(gc, finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200448 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 }
450 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000451}
452
Antoine Pitrou796564c2013-07-30 19:59:21 +0200453/* A traversal callback for move_legacy_finalizer_reachable. */
Tim Peters19b74c72002-07-01 03:52:19 +0000454static int
455visit_move(PyObject *op, PyGC_Head *tolist)
456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (PyObject_IS_GC(op)) {
458 if (IS_TENTATIVELY_UNREACHABLE(op)) {
459 PyGC_Head *gc = AS_GC(op);
460 gc_list_move(gc, tolist);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200461 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 }
463 }
464 return 0;
Tim Peters19b74c72002-07-01 03:52:19 +0000465}
466
467/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersf6b80452003-04-07 19:21:15 +0000468 * into finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000469 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000470static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200471move_legacy_finalizer_reachable(PyGC_Head *finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 traverseproc traverse;
474 PyGC_Head *gc = finalizers->gc.gc_next;
475 for (; gc != finalizers; gc = gc->gc.gc_next) {
476 /* Note that the finalizers list may grow during this. */
477 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
478 (void) traverse(FROM_GC(gc),
479 (visitproc)visit_move,
480 (void *)finalizers);
481 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000482}
483
Tim Petersead8b7a2004-10-30 23:09:22 +0000484/* Clear all weakrefs to unreachable objects, and if such a weakref has a
485 * callback, invoke it if necessary. Note that it's possible for such
486 * weakrefs to be outside the unreachable set -- indeed, those are precisely
487 * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
488 * overview & some details. Some weakrefs with callbacks may be reclaimed
489 * directly by this routine; the number reclaimed is the return value. Other
490 * weakrefs with callbacks may be moved into the `old` generation. Objects
491 * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
492 * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
493 * no object in `unreachable` is weakly referenced anymore.
Tim Peters403a2032003-11-20 21:21:46 +0000494 */
495static int
Tim Petersead8b7a2004-10-30 23:09:22 +0000496handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
Tim Peters403a2032003-11-20 21:21:46 +0000497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 PyGC_Head *gc;
499 PyObject *op; /* generally FROM_GC(gc) */
500 PyWeakReference *wr; /* generally a cast of op */
501 PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
502 PyGC_Head *next;
503 int num_freed = 0;
Tim Peters403a2032003-11-20 21:21:46 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 gc_list_init(&wrcb_to_call);
Tim Peters403a2032003-11-20 21:21:46 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Clear all weakrefs to the objects in unreachable. If such a weakref
508 * also has a callback, move it into `wrcb_to_call` if the callback
509 * needs to be invoked. Note that we cannot invoke any callbacks until
510 * all weakrefs to unreachable objects are cleared, lest the callback
511 * resurrect an unreachable object via a still-active weakref. We
512 * make another pass over wrcb_to_call, invoking callbacks, after this
513 * pass completes.
514 */
515 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
516 PyWeakReference **wrlist;
Tim Petersead8b7a2004-10-30 23:09:22 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 op = FROM_GC(gc);
519 assert(IS_TENTATIVELY_UNREACHABLE(op));
520 next = gc->gc.gc_next;
Tim Petersead8b7a2004-10-30 23:09:22 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
523 continue;
Tim Petersead8b7a2004-10-30 23:09:22 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* It supports weakrefs. Does it have any? */
526 wrlist = (PyWeakReference **)
527 PyObject_GET_WEAKREFS_LISTPTR(op);
Tim Petersead8b7a2004-10-30 23:09:22 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* `op` may have some weakrefs. March over the list, clear
530 * all the weakrefs, and move the weakrefs with callbacks
531 * that must be called into wrcb_to_call.
532 */
533 for (wr = *wrlist; wr != NULL; wr = *wrlist) {
534 PyGC_Head *wrasgc; /* AS_GC(wr) */
Tim Petersead8b7a2004-10-30 23:09:22 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* _PyWeakref_ClearRef clears the weakref but leaves
537 * the callback pointer intact. Obscure: it also
538 * changes *wrlist.
539 */
540 assert(wr->wr_object == op);
541 _PyWeakref_ClearRef(wr);
542 assert(wr->wr_object == Py_None);
543 if (wr->wr_callback == NULL)
544 continue; /* no callback */
Tim Petersead8b7a2004-10-30 23:09:22 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 /* Headache time. `op` is going away, and is weakly referenced by
547 * `wr`, which has a callback. Should the callback be invoked? If wr
548 * is also trash, no:
549 *
550 * 1. There's no need to call it. The object and the weakref are
551 * both going away, so it's legitimate to pretend the weakref is
552 * going away first. The user has to ensure a weakref outlives its
553 * referent if they want a guarantee that the wr callback will get
554 * invoked.
555 *
556 * 2. It may be catastrophic to call it. If the callback is also in
557 * cyclic trash (CT), then although the CT is unreachable from
558 * outside the current generation, CT may be reachable from the
559 * callback. Then the callback could resurrect insane objects.
560 *
561 * Since the callback is never needed and may be unsafe in this case,
562 * wr is simply left in the unreachable set. Note that because we
563 * already called _PyWeakref_ClearRef(wr), its callback will never
564 * trigger.
565 *
566 * OTOH, if wr isn't part of CT, we should invoke the callback: the
567 * weakref outlived the trash. Note that since wr isn't CT in this
568 * case, its callback can't be CT either -- wr acted as an external
569 * root to this generation, and therefore its callback did too. So
570 * nothing in CT is reachable from the callback either, so it's hard
571 * to imagine how calling it later could create a problem for us. wr
572 * is moved to wrcb_to_call in this case.
573 */
574 if (IS_TENTATIVELY_UNREACHABLE(wr))
575 continue;
576 assert(IS_REACHABLE(wr));
Tim Peterscc2a8662004-10-31 22:12:43 +0000577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 /* Create a new reference so that wr can't go away
579 * before we can process it again.
580 */
581 Py_INCREF(wr);
Tim Petersead8b7a2004-10-30 23:09:22 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 /* Move wr to wrcb_to_call, for the next pass. */
584 wrasgc = AS_GC(wr);
585 assert(wrasgc != next); /* wrasgc is reachable, but
586 next isn't, so they can't
587 be the same */
588 gc_list_move(wrasgc, &wrcb_to_call);
589 }
590 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 /* Invoke the callbacks we decided to honor. It's safe to invoke them
593 * because they can't reference unreachable objects.
594 */
595 while (! gc_list_is_empty(&wrcb_to_call)) {
596 PyObject *temp;
597 PyObject *callback;
Tim Petersead8b7a2004-10-30 23:09:22 +0000598
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 gc = wrcb_to_call.gc.gc_next;
600 op = FROM_GC(gc);
601 assert(IS_REACHABLE(op));
602 assert(PyWeakref_Check(op));
603 wr = (PyWeakReference *)op;
604 callback = wr->wr_callback;
605 assert(callback != NULL);
Tim Petersead8b7a2004-10-30 23:09:22 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* copy-paste of weakrefobject.c's handle_callback() */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100608 temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (temp == NULL)
610 PyErr_WriteUnraisable(callback);
611 else
612 Py_DECREF(temp);
Tim Petersead8b7a2004-10-30 23:09:22 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* Give up the reference we created in the first pass. When
615 * op's refcount hits 0 (which it may or may not do right now),
616 * op's tp_dealloc will decref op->wr_callback too. Note
617 * that the refcount probably will hit 0 now, and because this
618 * weakref was reachable to begin with, gc didn't already
619 * add it to its count of freed objects. Example: a reachable
620 * weak value dict maps some key to this reachable weakref.
621 * The callback removes this key->weakref mapping from the
622 * dict, leaving no other references to the weakref (excepting
623 * ours).
624 */
625 Py_DECREF(op);
626 if (wrcb_to_call.gc.gc_next == gc) {
627 /* object is still alive -- move it */
628 gc_list_move(gc, old);
629 }
630 else
631 ++num_freed;
632 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return num_freed;
Tim Peters403a2032003-11-20 21:21:46 +0000635}
636
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000637static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200638debug_cycle(const char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000639{
Victor Stinner499dfcf2011-03-21 13:26:24 +0100640 PySys_FormatStderr("gc: %s <%s %p>\n",
641 msg, Py_TYPE(op)->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000642}
643
Antoine Pitrou796564c2013-07-30 19:59:21 +0200644/* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
Tim Petersbf384c22003-04-06 00:11:39 +0000645 * only from such cycles).
Tim Petersf6b80452003-04-07 19:21:15 +0000646 * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
647 * garbage list (a Python list), else only the objects in finalizers with
648 * __del__ methods are appended to garbage. All objects in finalizers are
649 * merged into the old list regardless.
Tim Peters259272b2003-04-06 19:41:39 +0000650 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
651 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000652 */
Tim Peters259272b2003-04-06 19:41:39 +0000653static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200654handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersf6b80452003-04-07 19:21:15 +0000657
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 if (_PyRuntime.gc.garbage == NULL) {
659 _PyRuntime.gc.garbage = PyList_New(0);
660 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 Py_FatalError("gc couldn't create gc.garbage list");
662 }
663 for (; gc != finalizers; gc = gc->gc.gc_next) {
664 PyObject *op = FROM_GC(gc);
Tim Petersf6b80452003-04-07 19:21:15 +0000665
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600666 if ((_PyRuntime.gc.debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {
667 if (PyList_Append(_PyRuntime.gc.garbage, op) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return -1;
669 }
670 }
Tim Petersf6b80452003-04-07 19:21:15 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 gc_list_merge(finalizers, old);
673 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000674}
675
Tim Peters5fbc7b12014-05-08 17:42:19 -0500676/* Run first-time finalizers (if any) on all the objects in collectable.
677 * Note that this may remove some (or even all) of the objects from the
678 * list, due to refcounts falling to 0.
679 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200680static void
Tim Peters5fbc7b12014-05-08 17:42:19 -0500681finalize_garbage(PyGC_Head *collectable)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200682{
683 destructor finalize;
Tim Peters5fbc7b12014-05-08 17:42:19 -0500684 PyGC_Head seen;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200685
Tim Peters5fbc7b12014-05-08 17:42:19 -0500686 /* While we're going through the loop, `finalize(op)` may cause op, or
687 * other objects, to be reclaimed via refcounts falling to zero. So
688 * there's little we can rely on about the structure of the input
689 * `collectable` list across iterations. For safety, we always take the
690 * first object in that list and move it to a temporary `seen` list.
691 * If objects vanish from the `collectable` and `seen` lists we don't
692 * care.
693 */
694 gc_list_init(&seen);
695
696 while (!gc_list_is_empty(collectable)) {
697 PyGC_Head *gc = collectable->gc.gc_next;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200698 PyObject *op = FROM_GC(gc);
Tim Peters5fbc7b12014-05-08 17:42:19 -0500699 gc_list_move(gc, &seen);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200700 if (!_PyGCHead_FINALIZED(gc) &&
Tim Peters5fbc7b12014-05-08 17:42:19 -0500701 PyType_HasFeature(Py_TYPE(op), Py_TPFLAGS_HAVE_FINALIZE) &&
702 (finalize = Py_TYPE(op)->tp_finalize) != NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200703 _PyGCHead_SET_FINALIZED(gc, 1);
704 Py_INCREF(op);
705 finalize(op);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200706 Py_DECREF(op);
707 }
708 }
Tim Peters5fbc7b12014-05-08 17:42:19 -0500709 gc_list_merge(&seen, collectable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200710}
711
712/* Walk the collectable list and check that they are really unreachable
713 from the outside (some objects could have been resurrected by a
714 finalizer). */
715static int
716check_garbage(PyGC_Head *collectable)
717{
718 PyGC_Head *gc;
719 for (gc = collectable->gc.gc_next; gc != collectable;
720 gc = gc->gc.gc_next) {
721 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
722 assert(_PyGCHead_REFS(gc) != 0);
723 }
724 subtract_refs(collectable);
725 for (gc = collectable->gc.gc_next; gc != collectable;
726 gc = gc->gc.gc_next) {
727 assert(_PyGCHead_REFS(gc) >= 0);
728 if (_PyGCHead_REFS(gc) != 0)
729 return -1;
730 }
731 return 0;
732}
733
734static void
735revive_garbage(PyGC_Head *collectable)
736{
737 PyGC_Head *gc;
738 for (gc = collectable->gc.gc_next; gc != collectable;
739 gc = gc->gc.gc_next) {
740 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
741 }
742}
743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000745 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000746 * objects may be freed. It is possible I screwed something up here.
747 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000748static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000749delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 inquiry clear;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 while (!gc_list_is_empty(collectable)) {
754 PyGC_Head *gc = collectable->gc.gc_next;
755 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000756
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600757 if (_PyRuntime.gc.debug & DEBUG_SAVEALL) {
758 PyList_Append(_PyRuntime.gc.garbage, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 }
760 else {
761 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
762 Py_INCREF(op);
763 clear(op);
764 Py_DECREF(op);
765 }
766 }
767 if (collectable->gc.gc_next == gc) {
768 /* object is still alive, move it, it may die later */
769 gc_list_move(gc, old);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200770 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 }
772 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000773}
774
Christian Heimesa156e092008-02-16 07:38:31 +0000775/* Clear all free lists
776 * All free lists are cleared during the collection of the highest generation.
777 * Allocated items in the free list may keep a pymalloc arena occupied.
778 * Clearing the free lists may give back memory to the OS earlier.
779 */
780static void
781clear_freelists(void)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 (void)PyMethod_ClearFreeList();
784 (void)PyFrame_ClearFreeList();
785 (void)PyCFunction_ClearFreeList();
786 (void)PyTuple_ClearFreeList();
787 (void)PyUnicode_ClearFreeList();
788 (void)PyFloat_ClearFreeList();
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100789 (void)PyList_ClearFreeList();
790 (void)PyDict_ClearFreeList();
Antoine Pitrou093ce9c2011-12-16 11:24:27 +0100791 (void)PySet_ClearFreeList();
Yury Selivanoveb636452016-09-08 22:01:51 -0700792 (void)PyAsyncGen_ClearFreeLists();
Christian Heimesa156e092008-02-16 07:38:31 +0000793}
794
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000795/* This is the main function. Read this to understand how the
796 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000797static Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +0200798collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
799 int nofail)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 int i;
802 Py_ssize_t m = 0; /* # objects collected */
803 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
804 PyGC_Head *young; /* the generation we are examining */
805 PyGC_Head *old; /* next older generation */
806 PyGC_Head unreachable; /* non-problematic unreachable trash */
807 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
808 PyGC_Head *gc;
Victor Stinner7181dec2015-03-27 17:47:53 +0100809 _PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200810
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600811 struct gc_generation_stats *stats = &_PyRuntime.gc.generation_stats[generation];
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000812
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600813 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 PySys_WriteStderr("gc: collecting generation %d...\n",
815 generation);
816 PySys_WriteStderr("gc: objects in each generation:");
817 for (i = 0; i < NUM_GENERATIONS; i++)
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200818 PySys_FormatStderr(" %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 gc_list_size(GEN_HEAD(i)));
brainfvckc75edab2017-10-16 12:49:41 -0700820 PySys_WriteStderr("\ngc: objects in permanent generation: %zd",
821 gc_list_size(&_PyRuntime.gc.permanent_generation.head));
Victor Stinner7181dec2015-03-27 17:47:53 +0100822 t1 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PySys_WriteStderr("\n");
825 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000826
Łukasz Langaa785c872016-09-09 17:37:37 -0700827 if (PyDTrace_GC_START_ENABLED())
828 PyDTrace_GC_START(generation);
829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* update collection and allocation counters */
831 if (generation+1 < NUM_GENERATIONS)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600832 _PyRuntime.gc.generations[generation+1].count += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 for (i = 0; i <= generation; i++)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600834 _PyRuntime.gc.generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 /* merge younger generations with one we are currently collecting */
837 for (i = 0; i < generation; i++) {
838 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
839 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 /* handy references */
842 young = GEN_HEAD(generation);
843 if (generation < NUM_GENERATIONS-1)
844 old = GEN_HEAD(generation+1);
845 else
846 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* Using ob_refcnt and gc_refs, calculate which objects in the
849 * container set are reachable from outside the set (i.e., have a
850 * refcount greater than 0 when all the references within the
851 * set are taken into account).
852 */
853 update_refs(young);
854 subtract_refs(young);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 /* Leave everything reachable from outside young in young, and move
857 * everything else (in young) to unreachable.
858 * NOTE: This used to move the reachable objects into a reachable
859 * set instead. But most things usually turn out to be reachable,
860 * so it's more efficient to move the unreachable things.
861 */
862 gc_list_init(&unreachable);
863 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000864
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 /* Move reachable objects to next generation. */
866 if (young != old) {
867 if (generation == NUM_GENERATIONS - 2) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600868 _PyRuntime.gc.long_lived_pending += gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 }
870 gc_list_merge(young, old);
871 }
872 else {
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200873 /* We only untrack dicts in full collections, to avoid quadratic
874 dict build-up. See issue #14775. */
875 untrack_dicts(young);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600876 _PyRuntime.gc.long_lived_pending = 0;
877 _PyRuntime.gc.long_lived_total = gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* All objects in unreachable are trash, but objects reachable from
Antoine Pitrou796564c2013-07-30 19:59:21 +0200881 * legacy finalizers (e.g. tp_del) can't safely be deleted.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 */
883 gc_list_init(&finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200884 move_legacy_finalizers(&unreachable, &finalizers);
885 /* finalizers contains the unreachable objects with a legacy finalizer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 * unreachable objects reachable *from* those are also uncollectable,
887 * and we move those into the finalizers list too.
888 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200889 move_legacy_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 /* Collect statistics on collectable objects found and print
892 * debugging information.
893 */
894 for (gc = unreachable.gc.gc_next; gc != &unreachable;
895 gc = gc->gc.gc_next) {
896 m++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600897 if (_PyRuntime.gc.debug & DEBUG_COLLECTABLE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 debug_cycle("collectable", FROM_GC(gc));
899 }
900 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Clear weakrefs and invoke callbacks as necessary. */
903 m += handle_weakrefs(&unreachable, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000904
Antoine Pitrou796564c2013-07-30 19:59:21 +0200905 /* Call tp_finalize on objects which have one. */
Tim Peters5fbc7b12014-05-08 17:42:19 -0500906 finalize_garbage(&unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200907
908 if (check_garbage(&unreachable)) {
909 revive_garbage(&unreachable);
910 gc_list_merge(&unreachable, old);
911 }
912 else {
913 /* Call tp_clear on objects in the unreachable set. This will cause
914 * the reference cycles to be broken. It may also cause some objects
915 * in finalizers to be freed.
916 */
917 delete_garbage(&unreachable, old);
918 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* Collect statistics on uncollectable objects found and print
921 * debugging information. */
922 for (gc = finalizers.gc.gc_next;
923 gc != &finalizers;
924 gc = gc->gc.gc_next) {
925 n++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600926 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 debug_cycle("uncollectable", FROM_GC(gc));
928 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600929 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Victor Stinner7181dec2015-03-27 17:47:53 +0100930 _PyTime_t t2 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (m == 0 && n == 0)
933 PySys_WriteStderr("gc: done");
934 else
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200935 PySys_FormatStderr(
936 "gc: done, %zd unreachable, %zd uncollectable",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 n+m, n);
Victor Stinner7181dec2015-03-27 17:47:53 +0100938 PySys_WriteStderr(", %.4fs elapsed\n",
939 _PyTime_AsSecondsDouble(t2 - t1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Append instances in the uncollectable set to a Python
943 * reachable list of garbage. The programmer has to deal with
944 * this if they insist on creating this type of structure.
945 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200946 (void)handle_legacy_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* Clear free list only during the collection of the highest
949 * generation */
950 if (generation == NUM_GENERATIONS-1) {
951 clear_freelists();
952 }
Christian Heimesa156e092008-02-16 07:38:31 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (PyErr_Occurred()) {
Antoine Pitroufef34e32013-05-19 01:11:58 +0200955 if (nofail) {
956 PyErr_Clear();
957 }
958 else {
959 if (gc_str == NULL)
960 gc_str = PyUnicode_FromString("garbage collection");
961 PyErr_WriteUnraisable(gc_str);
962 Py_FatalError("unexpected exception during garbage collection");
963 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000965
Antoine Pitroud4156c12012-10-30 22:43:19 +0100966 /* Update stats */
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000967 if (n_collected)
968 *n_collected = m;
969 if (n_uncollectable)
970 *n_uncollectable = n;
Antoine Pitroud4156c12012-10-30 22:43:19 +0100971 stats->collections++;
972 stats->collected += m;
973 stats->uncollectable += n;
Łukasz Langaa785c872016-09-09 17:37:37 -0700974
975 if (PyDTrace_GC_DONE_ENABLED())
976 PyDTrace_GC_DONE(n+m);
977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return n+m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000979}
980
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000981/* Invoke progress callbacks to notify clients that garbage collection
982 * is starting or stopping
983 */
984static void
985invoke_gc_callback(const char *phase, int generation,
986 Py_ssize_t collected, Py_ssize_t uncollectable)
987{
988 Py_ssize_t i;
989 PyObject *info = NULL;
990
991 /* we may get called very early */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600992 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000993 return;
994 /* The local variable cannot be rebound, check it for sanity */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600995 assert(_PyRuntime.gc.callbacks != NULL && PyList_CheckExact(_PyRuntime.gc.callbacks));
996 if (PyList_GET_SIZE(_PyRuntime.gc.callbacks) != 0) {
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000997 info = Py_BuildValue("{sisnsn}",
998 "generation", generation,
999 "collected", collected,
1000 "uncollectable", uncollectable);
1001 if (info == NULL) {
1002 PyErr_WriteUnraisable(NULL);
1003 return;
1004 }
1005 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001006 for (i=0; i<PyList_GET_SIZE(_PyRuntime.gc.callbacks); i++) {
1007 PyObject *r, *cb = PyList_GET_ITEM(_PyRuntime.gc.callbacks, i);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001008 Py_INCREF(cb); /* make sure cb doesn't go away */
1009 r = PyObject_CallFunction(cb, "sO", phase, info);
1010 Py_XDECREF(r);
1011 if (r == NULL)
1012 PyErr_WriteUnraisable(cb);
1013 Py_DECREF(cb);
1014 }
1015 Py_XDECREF(info);
1016}
1017
1018/* Perform garbage collection of a generation and invoke
1019 * progress callbacks.
1020 */
1021static Py_ssize_t
1022collect_with_callback(int generation)
1023{
1024 Py_ssize_t result, collected, uncollectable;
1025 invoke_gc_callback("start", generation, 0, 0);
Antoine Pitroufef34e32013-05-19 01:11:58 +02001026 result = collect(generation, &collected, &uncollectable, 0);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001027 invoke_gc_callback("stop", generation, collected, uncollectable);
1028 return result;
1029}
1030
Neal Norwitz7b216c52006-03-04 20:01:53 +00001031static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001032collect_generations(void)
1033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 int i;
1035 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 /* Find the oldest generation (highest numbered) where the count
1038 * exceeds the threshold. Objects in the that generation and
1039 * generations younger than it will be collected. */
1040 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001041 if (_PyRuntime.gc.generations[i].count > _PyRuntime.gc.generations[i].threshold) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 /* Avoid quadratic performance degradation in number
1043 of tracked objects. See comments at the beginning
1044 of this file, and issue #4074.
1045 */
1046 if (i == NUM_GENERATIONS - 1
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001047 && _PyRuntime.gc.long_lived_pending < _PyRuntime.gc.long_lived_total / 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 continue;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001049 n = collect_with_callback(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 break;
1051 }
1052 }
1053 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001054}
1055
Serhiy Storchaka93260282017-02-04 11:19:59 +02001056#include "clinic/gcmodule.c.h"
1057
1058/*[clinic input]
1059gc.enable
1060
1061Enable automatic garbage collection.
1062[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001063
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001064static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001065gc_enable_impl(PyObject *module)
1066/*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001067{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001068 _PyRuntime.gc.enabled = 1;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001069 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001070}
1071
Serhiy Storchaka93260282017-02-04 11:19:59 +02001072/*[clinic input]
1073gc.disable
1074
1075Disable automatic garbage collection.
1076[clinic start generated code]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001077
1078static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001079gc_disable_impl(PyObject *module)
1080/*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a14e800d83b]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001081{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001082 _PyRuntime.gc.enabled = 0;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001083 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001084}
1085
Serhiy Storchaka93260282017-02-04 11:19:59 +02001086/*[clinic input]
1087gc.isenabled -> bool
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001088
Serhiy Storchaka93260282017-02-04 11:19:59 +02001089Returns true if automatic garbage collection is enabled.
1090[clinic start generated code]*/
1091
1092static int
1093gc_isenabled_impl(PyObject *module)
1094/*[clinic end generated code: output=1874298331c49130 input=30005e0422373b31]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001095{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001096 return _PyRuntime.gc.enabled;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001097}
1098
Serhiy Storchaka93260282017-02-04 11:19:59 +02001099/*[clinic input]
1100gc.collect -> Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001101
Serhiy Storchaka93260282017-02-04 11:19:59 +02001102 generation: int(c_default="NUM_GENERATIONS - 1") = 2
1103
1104Run the garbage collector.
1105
1106With no arguments, run a full collection. The optional argument
1107may be an integer specifying which generation to collect. A ValueError
1108is raised if the generation number is invalid.
1109
1110The number of unreachable objects is returned.
1111[clinic start generated code]*/
1112
1113static Py_ssize_t
1114gc_collect_impl(PyObject *module, int generation)
1115/*[clinic end generated code: output=b697e633043233c7 input=40720128b682d879]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001118
Serhiy Storchaka93260282017-02-04 11:19:59 +02001119 if (generation < 0 || generation >= NUM_GENERATIONS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 PyErr_SetString(PyExc_ValueError, "invalid generation");
Serhiy Storchaka93260282017-02-04 11:19:59 +02001121 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 }
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001123
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001124 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 n = 0; /* already collecting, don't do anything */
1126 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001127 _PyRuntime.gc.collecting = 1;
Serhiy Storchaka93260282017-02-04 11:19:59 +02001128 n = collect_with_callback(generation);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001129 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001131
Serhiy Storchaka93260282017-02-04 11:19:59 +02001132 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001133}
1134
Serhiy Storchaka93260282017-02-04 11:19:59 +02001135/*[clinic input]
1136gc.set_debug
1137
1138 flags: int
1139 An integer that can have the following bits turned on:
1140 DEBUG_STATS - Print statistics during collection.
1141 DEBUG_COLLECTABLE - Print collectable objects found.
1142 DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
1143 found.
1144 DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
1145 DEBUG_LEAK - Debug leaking programs (everything but STATS).
1146 /
1147
1148Set the garbage collection debugging flags.
1149
1150Debugging information is written to sys.stderr.
1151[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001152
1153static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001154gc_set_debug_impl(PyObject *module, int flags)
1155/*[clinic end generated code: output=7c8366575486b228 input=5e5ce15e84fbed15]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001156{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001157 _PyRuntime.gc.debug = flags;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001158
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001159 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001160}
1161
Serhiy Storchaka93260282017-02-04 11:19:59 +02001162/*[clinic input]
1163gc.get_debug -> int
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001164
Serhiy Storchaka93260282017-02-04 11:19:59 +02001165Get the garbage collection debugging flags.
1166[clinic start generated code]*/
1167
1168static int
1169gc_get_debug_impl(PyObject *module)
1170/*[clinic end generated code: output=91242f3506cd1e50 input=91a101e1c3b98366]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001171{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001172 return _PyRuntime.gc.debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001173}
1174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001175PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001176"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001177"\n"
1178"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001179"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001180
1181static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001182gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001183{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 int i;
1185 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001186 &_PyRuntime.gc.generations[0].threshold,
1187 &_PyRuntime.gc.generations[1].threshold,
1188 &_PyRuntime.gc.generations[2].threshold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return NULL;
1190 for (i = 2; i < NUM_GENERATIONS; i++) {
1191 /* generations higher than 2 get the same threshold */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001192 _PyRuntime.gc.generations[i].threshold = _PyRuntime.gc.generations[2].threshold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001194
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001195 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001196}
1197
Serhiy Storchaka93260282017-02-04 11:19:59 +02001198/*[clinic input]
1199gc.get_threshold
1200
1201Return the current collection thresholds.
1202[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001203
1204static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001205gc_get_threshold_impl(PyObject *module)
1206/*[clinic end generated code: output=7902bc9f41ecbbd8 input=286d79918034d6e6]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001209 _PyRuntime.gc.generations[0].threshold,
1210 _PyRuntime.gc.generations[1].threshold,
1211 _PyRuntime.gc.generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001212}
1213
Serhiy Storchaka93260282017-02-04 11:19:59 +02001214/*[clinic input]
1215gc.get_count
1216
1217Return a three-tuple of the current collection counts.
1218[clinic start generated code]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001219
1220static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001221gc_get_count_impl(PyObject *module)
1222/*[clinic end generated code: output=354012e67b16398f input=a392794a08251751]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001225 _PyRuntime.gc.generations[0].count,
1226 _PyRuntime.gc.generations[1].count,
1227 _PyRuntime.gc.generations[2].count);
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001228}
1229
Neil Schemenauer48c70342001-08-09 15:38:31 +00001230static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001231referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 Py_ssize_t i;
1234 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1235 if (PyTuple_GET_ITEM(objs, i) == obj)
1236 return 1;
1237 return 0;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001238}
1239
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001240static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001241gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 PyGC_Head *gc;
1244 PyObject *obj;
1245 traverseproc traverse;
1246 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
1247 obj = FROM_GC(gc);
1248 traverse = Py_TYPE(obj)->tp_traverse;
1249 if (obj == objs || obj == resultlist)
1250 continue;
1251 if (traverse(obj, (visitproc)referrersvisit, objs)) {
1252 if (PyList_Append(resultlist, obj) < 0)
1253 return 0; /* error */
1254 }
1255 }
1256 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001257}
1258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001259PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001260"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001262
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001263static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001264gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 int i;
1267 PyObject *result = PyList_New(0);
1268 if (!result) return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 for (i = 0; i < NUM_GENERATIONS; i++) {
1271 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1272 Py_DECREF(result);
1273 return NULL;
1274 }
1275 }
1276 return result;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001277}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001278
Tim Peters0f81ab62003-04-08 16:39:48 +00001279/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001280static int
Tim Peters730f5532003-04-08 17:17:17 +00001281referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001284}
1285
Tim Peters730f5532003-04-08 17:17:17 +00001286PyDoc_STRVAR(gc_get_referents__doc__,
1287"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001288Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001289
1290static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001291gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 Py_ssize_t i;
1294 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (result == NULL)
1297 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
1300 traverseproc traverse;
1301 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (! PyObject_IS_GC(obj))
1304 continue;
1305 traverse = Py_TYPE(obj)->tp_traverse;
1306 if (! traverse)
1307 continue;
1308 if (traverse(obj, (visitproc)referentsvisit, result)) {
1309 Py_DECREF(result);
1310 return NULL;
1311 }
1312 }
1313 return result;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001314}
1315
Serhiy Storchaka93260282017-02-04 11:19:59 +02001316/*[clinic input]
1317gc.get_objects
1318
1319Return a list of objects tracked by the collector (excluding the list returned).
1320[clinic start generated code]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001321
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001322static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001323gc_get_objects_impl(PyObject *module)
1324/*[clinic end generated code: output=fcb95d2e23e1f750 input=9439fe8170bf35d8]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 int i;
1327 PyObject* result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 result = PyList_New(0);
1330 if (result == NULL)
1331 return NULL;
1332 for (i = 0; i < NUM_GENERATIONS; i++) {
1333 if (append_objects(result, GEN_HEAD(i))) {
1334 Py_DECREF(result);
1335 return NULL;
1336 }
1337 }
1338 return result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001339}
1340
Serhiy Storchaka93260282017-02-04 11:19:59 +02001341/*[clinic input]
1342gc.get_stats
1343
1344Return a list of dictionaries containing per-generation statistics.
1345[clinic start generated code]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001346
1347static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001348gc_get_stats_impl(PyObject *module)
1349/*[clinic end generated code: output=a8ab1d8a5d26f3ab input=1ef4ed9d17b1a470]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001350{
1351 int i;
1352 PyObject *result;
1353 struct gc_generation_stats stats[NUM_GENERATIONS], *st;
1354
1355 /* To get consistent values despite allocations while constructing
1356 the result list, we use a snapshot of the running stats. */
1357 for (i = 0; i < NUM_GENERATIONS; i++) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001358 stats[i] = _PyRuntime.gc.generation_stats[i];
Antoine Pitroud4156c12012-10-30 22:43:19 +01001359 }
1360
1361 result = PyList_New(0);
1362 if (result == NULL)
1363 return NULL;
1364
1365 for (i = 0; i < NUM_GENERATIONS; i++) {
1366 PyObject *dict;
1367 st = &stats[i];
1368 dict = Py_BuildValue("{snsnsn}",
1369 "collections", st->collections,
1370 "collected", st->collected,
1371 "uncollectable", st->uncollectable
1372 );
1373 if (dict == NULL)
1374 goto error;
1375 if (PyList_Append(result, dict)) {
1376 Py_DECREF(dict);
1377 goto error;
1378 }
1379 Py_DECREF(dict);
1380 }
1381 return result;
1382
1383error:
1384 Py_XDECREF(result);
1385 return NULL;
1386}
1387
1388
Serhiy Storchaka93260282017-02-04 11:19:59 +02001389/*[clinic input]
1390gc.is_tracked
1391
1392 obj: object
1393 /
1394
1395Returns true if the object is tracked by the garbage collector.
1396
1397Simple atomic objects will return false.
1398[clinic start generated code]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001399
1400static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001401gc_is_tracked(PyObject *module, PyObject *obj)
1402/*[clinic end generated code: output=14f0103423b28e31 input=d83057f170ea2723]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyObject *result;
1405
1406 if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
1407 result = Py_True;
1408 else
1409 result = Py_False;
1410 Py_INCREF(result);
1411 return result;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001412}
1413
brainfvckc75edab2017-10-16 12:49:41 -07001414/*[clinic input]
1415gc.freeze
1416
1417Freeze all current tracked objects and ignore them for future collections.
1418
1419This can be used before a POSIX fork() call to make the gc copy-on-write friendly.
1420Note: collection before a POSIX fork() call may free pages for future allocation
1421which can cause copy-on-write.
1422[clinic start generated code]*/
1423
1424static PyObject *
1425gc_freeze_impl(PyObject *module)
1426/*[clinic end generated code: output=502159d9cdc4c139 input=b602b16ac5febbe5]*/
1427{
1428 for (int i = 0; i < NUM_GENERATIONS; ++i) {
1429 gc_list_merge(GEN_HEAD(i), &_PyRuntime.gc.permanent_generation.head);
1430 _PyRuntime.gc.generations[i].count = 0;
1431 }
1432 Py_RETURN_NONE;
1433}
1434
1435/*[clinic input]
1436gc.unfreeze
1437
1438Unfreeze all objects in the permanent generation.
1439
1440Put all objects in the permanent generation back into oldest generation.
1441[clinic start generated code]*/
1442
1443static PyObject *
1444gc_unfreeze_impl(PyObject *module)
1445/*[clinic end generated code: output=1c15f2043b25e169 input=2dd52b170f4cef6c]*/
1446{
1447 gc_list_merge(&_PyRuntime.gc.permanent_generation.head, GEN_HEAD(NUM_GENERATIONS-1));
1448 Py_RETURN_NONE;
1449}
1450
1451/*[clinic input]
1452gc.get_freeze_count -> int
1453
1454Return the number of objects in the permanent generation.
1455[clinic start generated code]*/
1456
1457static int
1458gc_get_freeze_count_impl(PyObject *module)
1459/*[clinic end generated code: output=e4e2ebcc77e5cbf3 input=4b759db880a3c6e4]*/
1460{
1461 return gc_list_size(&_PyRuntime.gc.permanent_generation.head);
1462}
1463
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001465PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001466"This module provides access to the garbage collector for reference cycles.\n"
1467"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001468"enable() -- Enable automatic garbage collection.\n"
1469"disable() -- Disable automatic garbage collection.\n"
1470"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001471"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001472"get_count() -- Return the current collection counts.\n"
R David Murray0e814632013-12-26 15:11:28 -05001473"get_stats() -- Return list of dictionaries containing per-generation stats.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001474"set_debug() -- Set debugging flags.\n"
1475"get_debug() -- Get debugging flags.\n"
1476"set_threshold() -- Set the collection thresholds.\n"
1477"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001478"get_objects() -- Return a list of all objects tracked by the collector.\n"
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001479"is_tracked() -- Returns true if a given object is tracked.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001480"get_referrers() -- Return the list of objects that refer to an object.\n"
brainfvckc75edab2017-10-16 12:49:41 -07001481"get_referents() -- Return the list of objects that an object refers to.\n"
1482"freeze() -- Freeze all tracked objects and ignore them for future collections.\n"
1483"unfreeze() -- Unfreeze all objects in the permanent generation.\n"
1484"get_freeze_count() -- Return the number of objects in the permanent generation.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001485
1486static PyMethodDef GcMethods[] = {
Serhiy Storchaka93260282017-02-04 11:19:59 +02001487 GC_ENABLE_METHODDEF
1488 GC_DISABLE_METHODDEF
1489 GC_ISENABLED_METHODDEF
1490 GC_SET_DEBUG_METHODDEF
1491 GC_GET_DEBUG_METHODDEF
1492 GC_GET_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Serhiy Storchaka93260282017-02-04 11:19:59 +02001494 GC_GET_THRESHOLD_METHODDEF
1495 GC_COLLECT_METHODDEF
1496 GC_GET_OBJECTS_METHODDEF
1497 GC_GET_STATS_METHODDEF
1498 GC_IS_TRACKED_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 {"get_referrers", gc_get_referrers, METH_VARARGS,
1500 gc_get_referrers__doc__},
1501 {"get_referents", gc_get_referents, METH_VARARGS,
1502 gc_get_referents__doc__},
brainfvckc75edab2017-10-16 12:49:41 -07001503 GC_FREEZE_METHODDEF
1504 GC_UNFREEZE_METHODDEF
1505 GC_GET_FREEZE_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 {NULL, NULL} /* Sentinel */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001507};
1508
Martin v. Löwis1a214512008-06-11 05:26:20 +00001509static struct PyModuleDef gcmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 PyModuleDef_HEAD_INIT,
Antoine Pitrou696e0352010-08-08 22:18:46 +00001511 "gc", /* m_name */
1512 gc__doc__, /* m_doc */
1513 -1, /* m_size */
1514 GcMethods, /* m_methods */
1515 NULL, /* m_reload */
1516 NULL, /* m_traverse */
1517 NULL, /* m_clear */
1518 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001519};
1520
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001521PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001522PyInit_gc(void)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 m = PyModule_Create(&gcmodule);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (m == NULL)
1529 return NULL;
Tim Peters11558872003-04-06 23:30:52 +00001530
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001531 if (_PyRuntime.gc.garbage == NULL) {
1532 _PyRuntime.gc.garbage = PyList_New(0);
1533 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 return NULL;
1535 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001536 Py_INCREF(_PyRuntime.gc.garbage);
1537 if (PyModule_AddObject(m, "garbage", _PyRuntime.gc.garbage) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001539
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001540 if (_PyRuntime.gc.callbacks == NULL) {
1541 _PyRuntime.gc.callbacks = PyList_New(0);
1542 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001543 return NULL;
1544 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001545 Py_INCREF(_PyRuntime.gc.callbacks);
1546 if (PyModule_AddObject(m, "callbacks", _PyRuntime.gc.callbacks) < 0)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001547 return NULL;
1548
Martin v. Löwis1a214512008-06-11 05:26:20 +00001549#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 ADD_INT(DEBUG_STATS);
1551 ADD_INT(DEBUG_COLLECTABLE);
1552 ADD_INT(DEBUG_UNCOLLECTABLE);
1553 ADD_INT(DEBUG_SAVEALL);
1554 ADD_INT(DEBUG_LEAK);
Tim Peters11558872003-04-06 23:30:52 +00001555#undef ADD_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 return m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001557}
1558
Guido van Rossume13ddc92003-04-17 17:29:22 +00001559/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001560Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001561PyGC_Collect(void)
1562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001564
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001565 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 n = 0; /* already collecting, don't do anything */
1567 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001568 _PyRuntime.gc.collecting = 1;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001569 n = collect_with_callback(NUM_GENERATIONS - 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001570 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 }
Guido van Rossume13ddc92003-04-17 17:29:22 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 return n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001574}
1575
Antoine Pitroufef34e32013-05-19 01:11:58 +02001576Py_ssize_t
Łukasz Langafef7e942016-09-09 21:47:46 -07001577_PyGC_CollectIfEnabled(void)
1578{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001579 if (!_PyRuntime.gc.enabled)
Łukasz Langafef7e942016-09-09 21:47:46 -07001580 return 0;
1581
1582 return PyGC_Collect();
1583}
1584
1585Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +02001586_PyGC_CollectNoFail(void)
1587{
1588 Py_ssize_t n;
1589
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001590 /* Ideally, this function is only called on interpreter shutdown,
1591 and therefore not recursively. Unfortunately, when there are daemon
1592 threads, a daemon thread can start a cyclic garbage collection
1593 during interpreter shutdown (and then never finish it).
1594 See http://bugs.python.org/issue8713#msg195178 for an example.
1595 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001596 if (_PyRuntime.gc.collecting)
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001597 n = 0;
1598 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001599 _PyRuntime.gc.collecting = 1;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001600 n = collect(NUM_GENERATIONS - 1, NULL, NULL, 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001601 _PyRuntime.gc.collecting = 0;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001602 }
Antoine Pitroufef34e32013-05-19 01:11:58 +02001603 return n;
1604}
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001605
Antoine Pitrou696e0352010-08-08 22:18:46 +00001606void
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001607_PyGC_DumpShutdownStats(void)
Antoine Pitrou696e0352010-08-08 22:18:46 +00001608{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001609 if (!(_PyRuntime.gc.debug & DEBUG_SAVEALL)
1610 && _PyRuntime.gc.garbage != NULL && PyList_GET_SIZE(_PyRuntime.gc.garbage) > 0) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001611 const char *message;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001612 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitroub5d82042010-11-05 00:05:25 +00001613 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001614 "shutdown";
1615 else
Antoine Pitroub5d82042010-11-05 00:05:25 +00001616 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001617 "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001618 /* PyErr_WarnFormat does too many things and we are at shutdown,
1619 the warnings module's dependencies (e.g. linecache) may be gone
1620 already. */
1621 if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1622 "gc", NULL, message,
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001623 PyList_GET_SIZE(_PyRuntime.gc.garbage)))
Georg Brandl08be72d2010-10-24 15:11:22 +00001624 PyErr_WriteUnraisable(NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001625 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE) {
Antoine Pitrou696e0352010-08-08 22:18:46 +00001626 PyObject *repr = NULL, *bytes = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001627 repr = PyObject_Repr(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001628 if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001629 PyErr_WriteUnraisable(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001630 else {
1631 PySys_WriteStderr(
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001632 " %s\n",
Antoine Pitrou696e0352010-08-08 22:18:46 +00001633 PyBytes_AS_STRING(bytes)
1634 );
1635 }
1636 Py_XDECREF(repr);
1637 Py_XDECREF(bytes);
1638 }
Antoine Pitrou696e0352010-08-08 22:18:46 +00001639 }
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001640}
1641
1642void
1643_PyGC_Fini(void)
1644{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001645 Py_CLEAR(_PyRuntime.gc.callbacks);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001646}
1647
Neil Schemenauer43411b52001-08-30 00:05:51 +00001648/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001649void
1650_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 _PyObject_Dump(FROM_GC(g));
Neil Schemenauer43411b52001-08-30 00:05:51 +00001653}
1654
Neil Schemenauer43411b52001-08-30 00:05:51 +00001655/* extension modules might be compiled with GC support so these
1656 functions must always be available */
1657
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001658#undef PyObject_GC_Track
1659#undef PyObject_GC_UnTrack
1660#undef PyObject_GC_Del
1661#undef _PyObject_GC_Malloc
1662
Neil Schemenauer43411b52001-08-30 00:05:51 +00001663void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001664PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 _PyObject_GC_TRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001667}
1668
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001669void
1670PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1673 * call PyObject_GC_UnTrack twice on an object.
1674 */
1675 if (IS_TRACKED(op))
1676 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001677}
1678
Victor Stinnerdb067af2014-05-02 22:31:14 +02001679static PyObject *
1680_PyObject_GC_Alloc(int use_calloc, size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PyObject *op;
1683 PyGC_Head *g;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001684 size_t size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1686 return PyErr_NoMemory();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001687 size = sizeof(PyGC_Head) + basicsize;
1688 if (use_calloc)
1689 g = (PyGC_Head *)PyObject_Calloc(1, size);
1690 else
1691 g = (PyGC_Head *)PyObject_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 if (g == NULL)
1693 return PyErr_NoMemory();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001694 g->gc.gc_refs = 0;
1695 _PyGCHead_SET_REFS(g, GC_UNTRACKED);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001696 _PyRuntime.gc.generations[0].count++; /* number of allocated GC objects */
1697 if (_PyRuntime.gc.generations[0].count > _PyRuntime.gc.generations[0].threshold &&
1698 _PyRuntime.gc.enabled &&
1699 _PyRuntime.gc.generations[0].threshold &&
1700 !_PyRuntime.gc.collecting &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 !PyErr_Occurred()) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001702 _PyRuntime.gc.collecting = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 collect_generations();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001704 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 }
1706 op = FROM_GC(g);
1707 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001708}
1709
1710PyObject *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001711_PyObject_GC_Malloc(size_t basicsize)
1712{
1713 return _PyObject_GC_Alloc(0, basicsize);
1714}
1715
1716PyObject *
1717_PyObject_GC_Calloc(size_t basicsize)
1718{
1719 return _PyObject_GC_Alloc(1, basicsize);
1720}
1721
1722PyObject *
Neil Schemenauer43411b52001-08-30 00:05:51 +00001723_PyObject_GC_New(PyTypeObject *tp)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
1726 if (op != NULL)
1727 op = PyObject_INIT(op, tp);
1728 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001729}
1730
1731PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001732_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001733{
Victor Stinner5d1866c2013-07-08 22:17:52 +02001734 size_t size;
1735 PyVarObject *op;
1736
1737 if (nitems < 0) {
1738 PyErr_BadInternalCall();
1739 return NULL;
1740 }
1741 size = _PyObject_VAR_SIZE(tp, nitems);
1742 op = (PyVarObject *) _PyObject_GC_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 if (op != NULL)
1744 op = PyObject_INIT_VAR(op, tp, nitems);
1745 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001746}
1747
1748PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001749_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
1752 PyGC_Head *g = AS_GC(op);
1753 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1754 return (PyVarObject *)PyErr_NoMemory();
1755 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
1756 if (g == NULL)
1757 return (PyVarObject *)PyErr_NoMemory();
1758 op = (PyVarObject *) FROM_GC(g);
1759 Py_SIZE(op) = nitems;
1760 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001761}
1762
1763void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001764PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001765{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 PyGC_Head *g = AS_GC(op);
1767 if (IS_TRACKED(op))
1768 gc_list_remove(g);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001769 if (_PyRuntime.gc.generations[0].count > 0) {
1770 _PyRuntime.gc.generations[0].count--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 }
1772 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001773}