blob: 7d23fc22c81dd03cd31e8184bd880d5705f1aa0a [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"
Yury Selivanovf23746a2018-01-22 19:11:18 -050027#include "internal/context.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060028#include "internal/mem.h"
29#include "internal/pystate.h"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000030#include "frameobject.h" /* for PyFrame_ClearFreeList */
Łukasz Langaa785c872016-09-09 17:37:37 -070031#include "pydtrace.h"
Victor Stinner7181dec2015-03-27 17:47:53 +010032#include "pytime.h" /* for _PyTime_GetMonotonicClock() */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000033
Serhiy Storchaka93260282017-02-04 11:19:59 +020034/*[clinic input]
35module gc
36[clinic start generated code]*/
37/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b5c9690ecc842d79]*/
38
Neil Schemenauer43411b52001-08-30 00:05:51 +000039/* Get an object's GC head */
40#define AS_GC(o) ((PyGC_Head *)(o)-1)
41
42/* Get the object given the GC head */
43#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
44
Tim Peters6fc13d92002-07-02 18:12:35 +000045/* Python string to use if unhandled exception occurs */
Tim Petersbf384c22003-04-06 00:11:39 +000046static PyObject *gc_str = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000047
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000048/* set for debugging information */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049#define DEBUG_STATS (1<<0) /* print collection statistics */
50#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
51#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
52#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
53#define DEBUG_LEAK DEBUG_COLLECTABLE | \
54 DEBUG_UNCOLLECTABLE | \
55 DEBUG_SAVEALL
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000056
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057#define GEN_HEAD(n) (&_PyRuntime.gc.generations[n].head)
Antoine Pitroud4156c12012-10-30 22:43:19 +010058
Eric Snow2ebc5ce2017-09-07 23:51:28 -060059void
60_PyGC_Initialize(struct _gc_runtime_state *state)
61{
62 state->enabled = 1; /* automatic collection enabled? */
63
64#define _GEN_HEAD(n) (&state->generations[n].head)
65 struct gc_generation generations[NUM_GENERATIONS] = {
66 /* PyGC_Head, threshold, count */
67 {{{_GEN_HEAD(0), _GEN_HEAD(0), 0}}, 700, 0},
68 {{{_GEN_HEAD(1), _GEN_HEAD(1), 0}}, 10, 0},
69 {{{_GEN_HEAD(2), _GEN_HEAD(2), 0}}, 10, 0},
70 };
71 for (int i = 0; i < NUM_GENERATIONS; i++) {
72 state->generations[i] = generations[i];
73 };
74 state->generation0 = GEN_HEAD(0);
brainfvckc75edab2017-10-16 12:49:41 -070075 struct gc_generation permanent_generation = {
76 {{&state->permanent_generation.head, &state->permanent_generation.head, 0}}, 0, 0
77 };
78 state->permanent_generation = permanent_generation;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079}
Antoine Pitroud4156c12012-10-30 22:43:19 +010080
Tim Peters6fc13d92002-07-02 18:12:35 +000081/*--------------------------------------------------------------------------
82gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +000083
Tim Peters6fc13d92002-07-02 18:12:35 +000084Between collections, every gc'ed object has one of two gc_refs values:
85
86GC_UNTRACKED
87 The initial state; objects returned by PyObject_GC_Malloc are in this
88 state. The object doesn't live in any generation list, and its
89 tp_traverse slot must not be called.
90
91GC_REACHABLE
92 The object lives in some generation list, and its tp_traverse is safe to
93 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
94 is called.
95
96During a collection, gc_refs can temporarily take on other states:
97
98>= 0
99 At the start of a collection, update_refs() copies the true refcount
100 to gc_refs, for each object in the generation being collected.
101 subtract_refs() then adjusts gc_refs so that it equals the number of
102 times an object is referenced directly from outside the generation
103 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +0000104 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000105
106GC_TENTATIVELY_UNREACHABLE
107 move_unreachable() then moves objects not reachable (whether directly or
108 indirectly) from outside the generation into an "unreachable" set.
109 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
110 again. Objects that are found to be unreachable have gc_refs set to
111 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
112 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
113 transition back to GC_REACHABLE.
114
115 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
116 for collection. If it's decided not to collect such an object (e.g.,
117 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
118----------------------------------------------------------------------------
119*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
121#define GC_REACHABLE _PyGC_REFS_REACHABLE
122#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000123
Antoine Pitrou796564c2013-07-30 19:59:21 +0200124#define IS_TRACKED(o) (_PyGC_REFS(o) != GC_UNTRACKED)
125#define IS_REACHABLE(o) (_PyGC_REFS(o) == GC_REACHABLE)
Tim Peters19b74c72002-07-01 03:52:19 +0000126#define IS_TENTATIVELY_UNREACHABLE(o) ( \
Antoine Pitrou796564c2013-07-30 19:59:21 +0200127 _PyGC_REFS(o) == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000128
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000129/*** list functions ***/
130
131static void
132gc_list_init(PyGC_Head *list)
133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 list->gc.gc_prev = list;
135 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000136}
137
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000138static int
139gc_list_is_empty(PyGC_Head *list)
140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return (list->gc.gc_next == list);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000142}
143
Tim Peterse2d59182004-11-01 01:39:08 +0000144#if 0
145/* This became unused after gc_list_move() was introduced. */
146/* Append `node` to `list`. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000147static void
148gc_list_append(PyGC_Head *node, PyGC_Head *list)
149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000150 node->gc.gc_next = list;
151 node->gc.gc_prev = list->gc.gc_prev;
152 node->gc.gc_prev->gc.gc_next = node;
153 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000154}
Tim Peterse2d59182004-11-01 01:39:08 +0000155#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000156
Tim Peterse2d59182004-11-01 01:39:08 +0000157/* Remove `node` from the gc list it's currently in. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000158static void
159gc_list_remove(PyGC_Head *node)
160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
162 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
163 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000164}
165
Tim Peterse2d59182004-11-01 01:39:08 +0000166/* Move `node` from the gc list it's currently in (which is not explicitly
167 * named here) to the end of `list`. This is semantically the same as
168 * gc_list_remove(node) followed by gc_list_append(node, list).
169 */
170static void
171gc_list_move(PyGC_Head *node, PyGC_Head *list)
172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 PyGC_Head *new_prev;
174 PyGC_Head *current_prev = node->gc.gc_prev;
175 PyGC_Head *current_next = node->gc.gc_next;
176 /* Unlink from current list. */
177 current_prev->gc.gc_next = current_next;
178 current_next->gc.gc_prev = current_prev;
179 /* Relink at end of new list. */
180 new_prev = node->gc.gc_prev = list->gc.gc_prev;
181 new_prev->gc.gc_next = list->gc.gc_prev = node;
182 node->gc.gc_next = list;
Tim Peterse2d59182004-11-01 01:39:08 +0000183}
184
185/* append list `from` onto list `to`; `from` becomes an empty list */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000186static void
187gc_list_merge(PyGC_Head *from, PyGC_Head *to)
188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 PyGC_Head *tail;
190 assert(from != to);
191 if (!gc_list_is_empty(from)) {
192 tail = to->gc.gc_prev;
193 tail->gc.gc_next = from->gc.gc_next;
194 tail->gc.gc_next->gc.gc_prev = tail;
195 to->gc.gc_prev = from->gc.gc_prev;
196 to->gc.gc_prev->gc.gc_next = to;
197 }
198 gc_list_init(from);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000199}
200
Neal Norwitz7b216c52006-03-04 20:01:53 +0000201static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000202gc_list_size(PyGC_Head *list)
203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyGC_Head *gc;
205 Py_ssize_t n = 0;
206 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
207 n++;
208 }
209 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000210}
211
Tim Peters259272b2003-04-06 19:41:39 +0000212/* Append objects in a GC list to a Python list.
213 * Return 0 if all OK, < 0 if error (out of memory for list).
214 */
215static int
216append_objects(PyObject *py_list, PyGC_Head *gc_list)
217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyGC_Head *gc;
219 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
220 PyObject *op = FROM_GC(gc);
221 if (op != py_list) {
222 if (PyList_Append(py_list, op)) {
223 return -1; /* exception */
224 }
225 }
226 }
227 return 0;
Tim Peters259272b2003-04-06 19:41:39 +0000228}
229
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000230/*** end of list stuff ***/
231
232
Tim Peters19b74c72002-07-01 03:52:19 +0000233/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
234 * in containers, and is GC_REACHABLE for all tracked gc objects not in
235 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000236 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000237static void
238update_refs(PyGC_Head *containers)
239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyGC_Head *gc = containers->gc.gc_next;
241 for (; gc != containers; gc = gc->gc.gc_next) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200242 assert(_PyGCHead_REFS(gc) == GC_REACHABLE);
243 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 /* Python's cyclic gc should never see an incoming refcount
245 * of 0: if something decref'ed to 0, it should have been
246 * deallocated immediately at that time.
247 * Possible cause (if the assert triggers): a tp_dealloc
248 * routine left a gc-aware object tracked during its teardown
249 * phase, and did something-- or allowed something to happen --
250 * that called back into Python. gc can trigger then, and may
251 * see the still-tracked dying object. Before this assert
252 * was added, such mistakes went on to allow gc to try to
253 * delete the object again. In a debug build, that caused
254 * a mysterious segfault, when _Py_ForgetReference tried
255 * to remove the object from the doubly-linked list of all
256 * objects a second time. In a release build, an actual
257 * double deallocation occurred, which leads to corruption
258 * of the allocator's internal bookkeeping pointers. That's
259 * so serious that maybe this should be a release-build
260 * check instead of an assert?
261 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200262 assert(_PyGCHead_REFS(gc) != 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000264}
265
Tim Peters19b74c72002-07-01 03:52:19 +0000266/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000267static int
268visit_decref(PyObject *op, void *data)
269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 assert(op != NULL);
271 if (PyObject_IS_GC(op)) {
272 PyGC_Head *gc = AS_GC(op);
273 /* We're only interested in gc_refs for objects in the
274 * generation being collected, which can be recognized
275 * because only they have positive gc_refs.
276 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200277 assert(_PyGCHead_REFS(gc) != 0); /* else refcount was too small */
278 if (_PyGCHead_REFS(gc) > 0)
279 _PyGCHead_DECREF(gc);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 }
281 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000282}
283
Tim Peters19b74c72002-07-01 03:52:19 +0000284/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
285 * for all objects in containers, and is GC_REACHABLE for all tracked gc
286 * objects not in containers. The ones with gc_refs > 0 are directly
287 * reachable from outside containers, and so can't be collected.
288 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000289static void
290subtract_refs(PyGC_Head *containers)
291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 traverseproc traverse;
293 PyGC_Head *gc = containers->gc.gc_next;
294 for (; gc != containers; gc=gc->gc.gc_next) {
295 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
296 (void) traverse(FROM_GC(gc),
297 (visitproc)visit_decref,
298 NULL);
299 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000300}
301
Tim Peters19b74c72002-07-01 03:52:19 +0000302/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000303static int
Tim Peters19b74c72002-07-01 03:52:19 +0000304visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 if (PyObject_IS_GC(op)) {
307 PyGC_Head *gc = AS_GC(op);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200308 const Py_ssize_t gc_refs = _PyGCHead_REFS(gc);
Tim Peters19b74c72002-07-01 03:52:19 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 if (gc_refs == 0) {
311 /* This is in move_unreachable's 'young' list, but
312 * the traversal hasn't yet gotten to it. All
313 * we need to do is tell move_unreachable that it's
314 * reachable.
315 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200316 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 }
318 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
319 /* This had gc_refs = 0 when move_unreachable got
320 * to it, but turns out it's reachable after all.
321 * Move it back to move_unreachable's 'young' list,
322 * and move_unreachable will eventually get to it
323 * again.
324 */
325 gc_list_move(gc, reachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200326 _PyGCHead_SET_REFS(gc, 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 }
328 /* Else there's nothing to do.
329 * If gc_refs > 0, it must be in move_unreachable's 'young'
330 * list, and move_unreachable will eventually get to it.
331 * If gc_refs == GC_REACHABLE, it's either in some other
332 * generation so we don't care about it, or move_unreachable
333 * already dealt with it.
334 * If gc_refs == GC_UNTRACKED, it must be ignored.
335 */
336 else {
337 assert(gc_refs > 0
338 || gc_refs == GC_REACHABLE
339 || gc_refs == GC_UNTRACKED);
340 }
341 }
342 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000343}
344
Tim Peters19b74c72002-07-01 03:52:19 +0000345/* Move the unreachable objects from young to unreachable. After this,
346 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
347 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
348 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
349 * All objects in young after this are directly or indirectly reachable
350 * from outside the original young; and all objects in unreachable are
351 * not.
Tim Peters88396172002-06-30 17:56:40 +0000352 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000353static void
Tim Peters19b74c72002-07-01 03:52:19 +0000354move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 PyGC_Head *gc = young->gc.gc_next;
Tim Peters19b74c72002-07-01 03:52:19 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 /* Invariants: all objects "to the left" of us in young have gc_refs
359 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
360 * from outside the young list as it was at entry. All other objects
361 * from the original young "to the left" of us are in unreachable now,
362 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
363 * left of us in 'young' now have been scanned, and no objects here
364 * or to the right have been scanned yet.
365 */
Tim Peters19b74c72002-07-01 03:52:19 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 while (gc != young) {
368 PyGC_Head *next;
Tim Peters19b74c72002-07-01 03:52:19 +0000369
Antoine Pitrou796564c2013-07-30 19:59:21 +0200370 if (_PyGCHead_REFS(gc)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 /* gc is definitely reachable from outside the
372 * original 'young'. Mark it as such, and traverse
373 * its pointers to find any other objects that may
374 * be directly reachable from it. Note that the
375 * call to tp_traverse may append objects to young,
376 * so we have to wait until it returns to determine
377 * the next object to visit.
378 */
379 PyObject *op = FROM_GC(gc);
380 traverseproc traverse = Py_TYPE(op)->tp_traverse;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200381 assert(_PyGCHead_REFS(gc) > 0);
382 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 (void) traverse(op,
384 (visitproc)visit_reachable,
385 (void *)young);
386 next = gc->gc.gc_next;
387 if (PyTuple_CheckExact(op)) {
388 _PyTuple_MaybeUntrack(op);
389 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 }
391 else {
392 /* This *may* be unreachable. To make progress,
393 * assume it is. gc isn't directly reachable from
394 * any object we've already traversed, but may be
395 * reachable from an object we haven't gotten to yet.
396 * visit_reachable will eventually move gc back into
397 * young if that's so, and we'll see it again.
398 */
399 next = gc->gc.gc_next;
400 gc_list_move(gc, unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200401 _PyGCHead_SET_REFS(gc, GC_TENTATIVELY_UNREACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 }
403 gc = next;
404 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000405}
406
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200407/* Try to untrack all currently tracked dictionaries */
408static void
409untrack_dicts(PyGC_Head *head)
410{
411 PyGC_Head *next, *gc = head->gc.gc_next;
412 while (gc != head) {
413 PyObject *op = FROM_GC(gc);
414 next = gc->gc.gc_next;
415 if (PyDict_CheckExact(op))
416 _PyDict_MaybeUntrack(op);
417 gc = next;
418 }
419}
420
Antoine Pitrou796564c2013-07-30 19:59:21 +0200421/* Return true if object has a pre-PEP 442 finalization method. */
Neil Schemenauera765c122001-11-01 17:35:23 +0000422static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200423has_legacy_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000424{
Antoine Pitrou796564c2013-07-30 19:59:21 +0200425 return op->ob_type->tp_del != NULL;
Neil Schemenauera765c122001-11-01 17:35:23 +0000426}
427
Antoine Pitrou796564c2013-07-30 19:59:21 +0200428/* Move the objects in unreachable with tp_del slots into `finalizers`.
Tim Petersead8b7a2004-10-30 23:09:22 +0000429 * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the
430 * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000431 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000432static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200433move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyGC_Head *gc;
436 PyGC_Head *next;
Tim Petersf6b80452003-04-07 19:21:15 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 /* March over unreachable. Move objects with finalizers into
439 * `finalizers`.
440 */
441 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
442 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 assert(IS_TENTATIVELY_UNREACHABLE(op));
445 next = gc->gc.gc_next;
Tim Petersf6ae7a42003-04-05 18:40:50 +0000446
Antoine Pitrou796564c2013-07-30 19:59:21 +0200447 if (has_legacy_finalizer(op)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 gc_list_move(gc, finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200449 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 }
451 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000452}
453
Antoine Pitrou796564c2013-07-30 19:59:21 +0200454/* A traversal callback for move_legacy_finalizer_reachable. */
Tim Peters19b74c72002-07-01 03:52:19 +0000455static int
456visit_move(PyObject *op, PyGC_Head *tolist)
457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (PyObject_IS_GC(op)) {
459 if (IS_TENTATIVELY_UNREACHABLE(op)) {
460 PyGC_Head *gc = AS_GC(op);
461 gc_list_move(gc, tolist);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200462 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 }
464 }
465 return 0;
Tim Peters19b74c72002-07-01 03:52:19 +0000466}
467
468/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersf6b80452003-04-07 19:21:15 +0000469 * into finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000470 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000471static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200472move_legacy_finalizer_reachable(PyGC_Head *finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 traverseproc traverse;
475 PyGC_Head *gc = finalizers->gc.gc_next;
476 for (; gc != finalizers; gc = gc->gc.gc_next) {
477 /* Note that the finalizers list may grow during this. */
478 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
479 (void) traverse(FROM_GC(gc),
480 (visitproc)visit_move,
481 (void *)finalizers);
482 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000483}
484
Tim Petersead8b7a2004-10-30 23:09:22 +0000485/* Clear all weakrefs to unreachable objects, and if such a weakref has a
486 * callback, invoke it if necessary. Note that it's possible for such
487 * weakrefs to be outside the unreachable set -- indeed, those are precisely
488 * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
489 * overview & some details. Some weakrefs with callbacks may be reclaimed
490 * directly by this routine; the number reclaimed is the return value. Other
491 * weakrefs with callbacks may be moved into the `old` generation. Objects
492 * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
493 * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
494 * no object in `unreachable` is weakly referenced anymore.
Tim Peters403a2032003-11-20 21:21:46 +0000495 */
496static int
Tim Petersead8b7a2004-10-30 23:09:22 +0000497handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
Tim Peters403a2032003-11-20 21:21:46 +0000498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyGC_Head *gc;
500 PyObject *op; /* generally FROM_GC(gc) */
501 PyWeakReference *wr; /* generally a cast of op */
502 PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
503 PyGC_Head *next;
504 int num_freed = 0;
Tim Peters403a2032003-11-20 21:21:46 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 gc_list_init(&wrcb_to_call);
Tim Peters403a2032003-11-20 21:21:46 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Clear all weakrefs to the objects in unreachable. If such a weakref
509 * also has a callback, move it into `wrcb_to_call` if the callback
510 * needs to be invoked. Note that we cannot invoke any callbacks until
511 * all weakrefs to unreachable objects are cleared, lest the callback
512 * resurrect an unreachable object via a still-active weakref. We
513 * make another pass over wrcb_to_call, invoking callbacks, after this
514 * pass completes.
515 */
516 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
517 PyWeakReference **wrlist;
Tim Petersead8b7a2004-10-30 23:09:22 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 op = FROM_GC(gc);
520 assert(IS_TENTATIVELY_UNREACHABLE(op));
521 next = gc->gc.gc_next;
Tim Petersead8b7a2004-10-30 23:09:22 +0000522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
524 continue;
Tim Petersead8b7a2004-10-30 23:09:22 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* It supports weakrefs. Does it have any? */
527 wrlist = (PyWeakReference **)
528 PyObject_GET_WEAKREFS_LISTPTR(op);
Tim Petersead8b7a2004-10-30 23:09:22 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 /* `op` may have some weakrefs. March over the list, clear
531 * all the weakrefs, and move the weakrefs with callbacks
532 * that must be called into wrcb_to_call.
533 */
534 for (wr = *wrlist; wr != NULL; wr = *wrlist) {
535 PyGC_Head *wrasgc; /* AS_GC(wr) */
Tim Petersead8b7a2004-10-30 23:09:22 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 /* _PyWeakref_ClearRef clears the weakref but leaves
538 * the callback pointer intact. Obscure: it also
539 * changes *wrlist.
540 */
541 assert(wr->wr_object == op);
542 _PyWeakref_ClearRef(wr);
543 assert(wr->wr_object == Py_None);
544 if (wr->wr_callback == NULL)
545 continue; /* no callback */
Tim Petersead8b7a2004-10-30 23:09:22 +0000546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 /* Headache time. `op` is going away, and is weakly referenced by
548 * `wr`, which has a callback. Should the callback be invoked? If wr
549 * is also trash, no:
550 *
551 * 1. There's no need to call it. The object and the weakref are
552 * both going away, so it's legitimate to pretend the weakref is
553 * going away first. The user has to ensure a weakref outlives its
554 * referent if they want a guarantee that the wr callback will get
555 * invoked.
556 *
557 * 2. It may be catastrophic to call it. If the callback is also in
558 * cyclic trash (CT), then although the CT is unreachable from
559 * outside the current generation, CT may be reachable from the
560 * callback. Then the callback could resurrect insane objects.
561 *
562 * Since the callback is never needed and may be unsafe in this case,
563 * wr is simply left in the unreachable set. Note that because we
564 * already called _PyWeakref_ClearRef(wr), its callback will never
565 * trigger.
566 *
567 * OTOH, if wr isn't part of CT, we should invoke the callback: the
568 * weakref outlived the trash. Note that since wr isn't CT in this
569 * case, its callback can't be CT either -- wr acted as an external
570 * root to this generation, and therefore its callback did too. So
571 * nothing in CT is reachable from the callback either, so it's hard
572 * to imagine how calling it later could create a problem for us. wr
573 * is moved to wrcb_to_call in this case.
574 */
575 if (IS_TENTATIVELY_UNREACHABLE(wr))
576 continue;
577 assert(IS_REACHABLE(wr));
Tim Peterscc2a8662004-10-31 22:12:43 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* Create a new reference so that wr can't go away
580 * before we can process it again.
581 */
582 Py_INCREF(wr);
Tim Petersead8b7a2004-10-30 23:09:22 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Move wr to wrcb_to_call, for the next pass. */
585 wrasgc = AS_GC(wr);
586 assert(wrasgc != next); /* wrasgc is reachable, but
587 next isn't, so they can't
588 be the same */
589 gc_list_move(wrasgc, &wrcb_to_call);
590 }
591 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 /* Invoke the callbacks we decided to honor. It's safe to invoke them
594 * because they can't reference unreachable objects.
595 */
596 while (! gc_list_is_empty(&wrcb_to_call)) {
597 PyObject *temp;
598 PyObject *callback;
Tim Petersead8b7a2004-10-30 23:09:22 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 gc = wrcb_to_call.gc.gc_next;
601 op = FROM_GC(gc);
602 assert(IS_REACHABLE(op));
603 assert(PyWeakref_Check(op));
604 wr = (PyWeakReference *)op;
605 callback = wr->wr_callback;
606 assert(callback != NULL);
Tim Petersead8b7a2004-10-30 23:09:22 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 /* copy-paste of weakrefobject.c's handle_callback() */
Victor Stinnerde4ae3d2016-12-04 22:59:09 +0100609 temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (temp == NULL)
611 PyErr_WriteUnraisable(callback);
612 else
613 Py_DECREF(temp);
Tim Petersead8b7a2004-10-30 23:09:22 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 /* Give up the reference we created in the first pass. When
616 * op's refcount hits 0 (which it may or may not do right now),
617 * op's tp_dealloc will decref op->wr_callback too. Note
618 * that the refcount probably will hit 0 now, and because this
619 * weakref was reachable to begin with, gc didn't already
620 * add it to its count of freed objects. Example: a reachable
621 * weak value dict maps some key to this reachable weakref.
622 * The callback removes this key->weakref mapping from the
623 * dict, leaving no other references to the weakref (excepting
624 * ours).
625 */
626 Py_DECREF(op);
627 if (wrcb_to_call.gc.gc_next == gc) {
628 /* object is still alive -- move it */
629 gc_list_move(gc, old);
630 }
631 else
632 ++num_freed;
633 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return num_freed;
Tim Peters403a2032003-11-20 21:21:46 +0000636}
637
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000638static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200639debug_cycle(const char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000640{
Victor Stinner499dfcf2011-03-21 13:26:24 +0100641 PySys_FormatStderr("gc: %s <%s %p>\n",
642 msg, Py_TYPE(op)->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000643}
644
Antoine Pitrou796564c2013-07-30 19:59:21 +0200645/* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
Tim Petersbf384c22003-04-06 00:11:39 +0000646 * only from such cycles).
Tim Petersf6b80452003-04-07 19:21:15 +0000647 * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
648 * garbage list (a Python list), else only the objects in finalizers with
649 * __del__ methods are appended to garbage. All objects in finalizers are
650 * merged into the old list regardless.
Tim Petersbf384c22003-04-06 00:11:39 +0000651 */
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +0300652static void
Antoine Pitrou796564c2013-07-30 19:59:21 +0200653handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersf6b80452003-04-07 19:21:15 +0000656
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300657 assert(!PyErr_Occurred());
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)) {
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300667 if (PyList_Append(_PyRuntime.gc.garbage, op) < 0) {
668 PyErr_Clear();
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +0300669 break;
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 }
672 }
Tim Petersf6b80452003-04-07 19:21:15 +0000673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 gc_list_merge(finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000675}
676
Tim Peters5fbc7b12014-05-08 17:42:19 -0500677/* Run first-time finalizers (if any) on all the objects in collectable.
678 * Note that this may remove some (or even all) of the objects from the
679 * list, due to refcounts falling to 0.
680 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200681static void
Tim Peters5fbc7b12014-05-08 17:42:19 -0500682finalize_garbage(PyGC_Head *collectable)
Antoine Pitrou796564c2013-07-30 19:59:21 +0200683{
684 destructor finalize;
Tim Peters5fbc7b12014-05-08 17:42:19 -0500685 PyGC_Head seen;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200686
Tim Peters5fbc7b12014-05-08 17:42:19 -0500687 /* While we're going through the loop, `finalize(op)` may cause op, or
688 * other objects, to be reclaimed via refcounts falling to zero. So
689 * there's little we can rely on about the structure of the input
690 * `collectable` list across iterations. For safety, we always take the
691 * first object in that list and move it to a temporary `seen` list.
692 * If objects vanish from the `collectable` and `seen` lists we don't
693 * care.
694 */
695 gc_list_init(&seen);
696
697 while (!gc_list_is_empty(collectable)) {
698 PyGC_Head *gc = collectable->gc.gc_next;
Antoine Pitrou796564c2013-07-30 19:59:21 +0200699 PyObject *op = FROM_GC(gc);
Tim Peters5fbc7b12014-05-08 17:42:19 -0500700 gc_list_move(gc, &seen);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200701 if (!_PyGCHead_FINALIZED(gc) &&
Tim Peters5fbc7b12014-05-08 17:42:19 -0500702 PyType_HasFeature(Py_TYPE(op), Py_TPFLAGS_HAVE_FINALIZE) &&
703 (finalize = Py_TYPE(op)->tp_finalize) != NULL) {
Antoine Pitrou796564c2013-07-30 19:59:21 +0200704 _PyGCHead_SET_FINALIZED(gc, 1);
705 Py_INCREF(op);
706 finalize(op);
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300707 assert(!PyErr_Occurred());
Antoine Pitrou796564c2013-07-30 19:59:21 +0200708 Py_DECREF(op);
709 }
710 }
Tim Peters5fbc7b12014-05-08 17:42:19 -0500711 gc_list_merge(&seen, collectable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200712}
713
714/* Walk the collectable list and check that they are really unreachable
715 from the outside (some objects could have been resurrected by a
716 finalizer). */
717static int
718check_garbage(PyGC_Head *collectable)
719{
720 PyGC_Head *gc;
721 for (gc = collectable->gc.gc_next; gc != collectable;
722 gc = gc->gc.gc_next) {
723 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
724 assert(_PyGCHead_REFS(gc) != 0);
725 }
726 subtract_refs(collectable);
727 for (gc = collectable->gc.gc_next; gc != collectable;
728 gc = gc->gc.gc_next) {
729 assert(_PyGCHead_REFS(gc) >= 0);
730 if (_PyGCHead_REFS(gc) != 0)
731 return -1;
732 }
733 return 0;
734}
735
736static void
737revive_garbage(PyGC_Head *collectable)
738{
739 PyGC_Head *gc;
740 for (gc = collectable->gc.gc_next; gc != collectable;
741 gc = gc->gc.gc_next) {
742 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
743 }
744}
745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000747 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000748 * objects may be freed. It is possible I screwed something up here.
749 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000750static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000751delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 inquiry clear;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000754
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300755 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 while (!gc_list_is_empty(collectable)) {
757 PyGC_Head *gc = collectable->gc.gc_next;
758 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000759
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600760 if (_PyRuntime.gc.debug & DEBUG_SAVEALL) {
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300761 assert(_PyRuntime.gc.garbage != NULL);
762 if (PyList_Append(_PyRuntime.gc.garbage, op) < 0) {
763 PyErr_Clear();
764 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 }
766 else {
767 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
768 Py_INCREF(op);
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300769 (void) clear(op);
770 if (PyErr_Occurred()) {
771 PySys_WriteStderr("Exception ignored in tp_clear of "
772 "%.50s\n", Py_TYPE(op)->tp_name);
773 PyErr_WriteUnraisable(NULL);
774 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 Py_DECREF(op);
776 }
777 }
778 if (collectable->gc.gc_next == gc) {
779 /* object is still alive, move it, it may die later */
780 gc_list_move(gc, old);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200781 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 }
783 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000784}
785
Christian Heimesa156e092008-02-16 07:38:31 +0000786/* Clear all free lists
787 * All free lists are cleared during the collection of the highest generation.
788 * Allocated items in the free list may keep a pymalloc arena occupied.
789 * Clearing the free lists may give back memory to the OS earlier.
790 */
791static void
792clear_freelists(void)
793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 (void)PyMethod_ClearFreeList();
795 (void)PyFrame_ClearFreeList();
796 (void)PyCFunction_ClearFreeList();
797 (void)PyTuple_ClearFreeList();
798 (void)PyUnicode_ClearFreeList();
799 (void)PyFloat_ClearFreeList();
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100800 (void)PyList_ClearFreeList();
801 (void)PyDict_ClearFreeList();
Antoine Pitrou093ce9c2011-12-16 11:24:27 +0100802 (void)PySet_ClearFreeList();
Yury Selivanoveb636452016-09-08 22:01:51 -0700803 (void)PyAsyncGen_ClearFreeLists();
Yury Selivanovf23746a2018-01-22 19:11:18 -0500804 (void)PyContext_ClearFreeList();
Christian Heimesa156e092008-02-16 07:38:31 +0000805}
806
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000807/* This is the main function. Read this to understand how the
808 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000809static Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +0200810collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
811 int nofail)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 int i;
814 Py_ssize_t m = 0; /* # objects collected */
815 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
816 PyGC_Head *young; /* the generation we are examining */
817 PyGC_Head *old; /* next older generation */
818 PyGC_Head unreachable; /* non-problematic unreachable trash */
819 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
820 PyGC_Head *gc;
Victor Stinner7181dec2015-03-27 17:47:53 +0100821 _PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200822
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600823 struct gc_generation_stats *stats = &_PyRuntime.gc.generation_stats[generation];
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000824
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PySys_WriteStderr("gc: collecting generation %d...\n",
827 generation);
828 PySys_WriteStderr("gc: objects in each generation:");
829 for (i = 0; i < NUM_GENERATIONS; i++)
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200830 PySys_FormatStderr(" %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 gc_list_size(GEN_HEAD(i)));
brainfvckc75edab2017-10-16 12:49:41 -0700832 PySys_WriteStderr("\ngc: objects in permanent generation: %zd",
833 gc_list_size(&_PyRuntime.gc.permanent_generation.head));
Victor Stinner7181dec2015-03-27 17:47:53 +0100834 t1 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PySys_WriteStderr("\n");
837 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000838
Łukasz Langaa785c872016-09-09 17:37:37 -0700839 if (PyDTrace_GC_START_ENABLED())
840 PyDTrace_GC_START(generation);
841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* update collection and allocation counters */
843 if (generation+1 < NUM_GENERATIONS)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600844 _PyRuntime.gc.generations[generation+1].count += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 for (i = 0; i <= generation; i++)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600846 _PyRuntime.gc.generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* merge younger generations with one we are currently collecting */
849 for (i = 0; i < generation; i++) {
850 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
851 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* handy references */
854 young = GEN_HEAD(generation);
855 if (generation < NUM_GENERATIONS-1)
856 old = GEN_HEAD(generation+1);
857 else
858 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 /* Using ob_refcnt and gc_refs, calculate which objects in the
861 * container set are reachable from outside the set (i.e., have a
862 * refcount greater than 0 when all the references within the
863 * set are taken into account).
864 */
865 update_refs(young);
866 subtract_refs(young);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 /* Leave everything reachable from outside young in young, and move
869 * everything else (in young) to unreachable.
870 * NOTE: This used to move the reachable objects into a reachable
871 * set instead. But most things usually turn out to be reachable,
872 * so it's more efficient to move the unreachable things.
873 */
874 gc_list_init(&unreachable);
875 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Move reachable objects to next generation. */
878 if (young != old) {
879 if (generation == NUM_GENERATIONS - 2) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600880 _PyRuntime.gc.long_lived_pending += gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 }
882 gc_list_merge(young, old);
883 }
884 else {
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200885 /* We only untrack dicts in full collections, to avoid quadratic
886 dict build-up. See issue #14775. */
887 untrack_dicts(young);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600888 _PyRuntime.gc.long_lived_pending = 0;
889 _PyRuntime.gc.long_lived_total = gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* All objects in unreachable are trash, but objects reachable from
Antoine Pitrou796564c2013-07-30 19:59:21 +0200893 * legacy finalizers (e.g. tp_del) can't safely be deleted.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 */
895 gc_list_init(&finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200896 move_legacy_finalizers(&unreachable, &finalizers);
897 /* finalizers contains the unreachable objects with a legacy finalizer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 * unreachable objects reachable *from* those are also uncollectable,
899 * and we move those into the finalizers list too.
900 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200901 move_legacy_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* Collect statistics on collectable objects found and print
904 * debugging information.
905 */
906 for (gc = unreachable.gc.gc_next; gc != &unreachable;
907 gc = gc->gc.gc_next) {
908 m++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600909 if (_PyRuntime.gc.debug & DEBUG_COLLECTABLE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 debug_cycle("collectable", FROM_GC(gc));
911 }
912 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000913
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 /* Clear weakrefs and invoke callbacks as necessary. */
915 m += handle_weakrefs(&unreachable, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000916
Antoine Pitrou796564c2013-07-30 19:59:21 +0200917 /* Call tp_finalize on objects which have one. */
Tim Peters5fbc7b12014-05-08 17:42:19 -0500918 finalize_garbage(&unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200919
920 if (check_garbage(&unreachable)) {
921 revive_garbage(&unreachable);
922 gc_list_merge(&unreachable, old);
923 }
924 else {
925 /* Call tp_clear on objects in the unreachable set. This will cause
926 * the reference cycles to be broken. It may also cause some objects
927 * in finalizers to be freed.
928 */
929 delete_garbage(&unreachable, old);
930 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 /* Collect statistics on uncollectable objects found and print
933 * debugging information. */
934 for (gc = finalizers.gc.gc_next;
935 gc != &finalizers;
936 gc = gc->gc.gc_next) {
937 n++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600938 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 debug_cycle("uncollectable", FROM_GC(gc));
940 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600941 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Victor Stinner7181dec2015-03-27 17:47:53 +0100942 _PyTime_t t2 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (m == 0 && n == 0)
945 PySys_WriteStderr("gc: done");
946 else
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200947 PySys_FormatStderr(
948 "gc: done, %zd unreachable, %zd uncollectable",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 n+m, n);
Victor Stinner7181dec2015-03-27 17:47:53 +0100950 PySys_WriteStderr(", %.4fs elapsed\n",
951 _PyTime_AsSecondsDouble(t2 - t1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Append instances in the uncollectable set to a Python
955 * reachable list of garbage. The programmer has to deal with
956 * this if they insist on creating this type of structure.
957 */
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +0300958 handle_legacy_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Clear free list only during the collection of the highest
961 * generation */
962 if (generation == NUM_GENERATIONS-1) {
963 clear_freelists();
964 }
Christian Heimesa156e092008-02-16 07:38:31 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 if (PyErr_Occurred()) {
Antoine Pitroufef34e32013-05-19 01:11:58 +0200967 if (nofail) {
968 PyErr_Clear();
969 }
970 else {
971 if (gc_str == NULL)
972 gc_str = PyUnicode_FromString("garbage collection");
973 PyErr_WriteUnraisable(gc_str);
974 Py_FatalError("unexpected exception during garbage collection");
975 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000977
Antoine Pitroud4156c12012-10-30 22:43:19 +0100978 /* Update stats */
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000979 if (n_collected)
980 *n_collected = m;
981 if (n_uncollectable)
982 *n_uncollectable = n;
Antoine Pitroud4156c12012-10-30 22:43:19 +0100983 stats->collections++;
984 stats->collected += m;
985 stats->uncollectable += n;
Łukasz Langaa785c872016-09-09 17:37:37 -0700986
987 if (PyDTrace_GC_DONE_ENABLED())
988 PyDTrace_GC_DONE(n+m);
989
Serhiy Storchakac4653c92018-05-29 18:50:10 +0300990 assert(!PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return n+m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000992}
993
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000994/* Invoke progress callbacks to notify clients that garbage collection
995 * is starting or stopping
996 */
997static void
998invoke_gc_callback(const char *phase, int generation,
999 Py_ssize_t collected, Py_ssize_t uncollectable)
1000{
1001 Py_ssize_t i;
1002 PyObject *info = NULL;
1003
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001004 assert(!PyErr_Occurred());
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001005 /* we may get called very early */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001006 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001007 return;
1008 /* The local variable cannot be rebound, check it for sanity */
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001009 assert(PyList_CheckExact(_PyRuntime.gc.callbacks));
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001010 if (PyList_GET_SIZE(_PyRuntime.gc.callbacks) != 0) {
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001011 info = Py_BuildValue("{sisnsn}",
1012 "generation", generation,
1013 "collected", collected,
1014 "uncollectable", uncollectable);
1015 if (info == NULL) {
1016 PyErr_WriteUnraisable(NULL);
1017 return;
1018 }
1019 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001020 for (i=0; i<PyList_GET_SIZE(_PyRuntime.gc.callbacks); i++) {
1021 PyObject *r, *cb = PyList_GET_ITEM(_PyRuntime.gc.callbacks, i);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001022 Py_INCREF(cb); /* make sure cb doesn't go away */
1023 r = PyObject_CallFunction(cb, "sO", phase, info);
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +03001024 if (r == NULL) {
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001025 PyErr_WriteUnraisable(cb);
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +03001026 }
1027 else {
1028 Py_DECREF(r);
1029 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001030 Py_DECREF(cb);
1031 }
1032 Py_XDECREF(info);
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001033 assert(!PyErr_Occurred());
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001034}
1035
1036/* Perform garbage collection of a generation and invoke
1037 * progress callbacks.
1038 */
1039static Py_ssize_t
1040collect_with_callback(int generation)
1041{
1042 Py_ssize_t result, collected, uncollectable;
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001043 assert(!PyErr_Occurred());
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001044 invoke_gc_callback("start", generation, 0, 0);
Antoine Pitroufef34e32013-05-19 01:11:58 +02001045 result = collect(generation, &collected, &uncollectable, 0);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001046 invoke_gc_callback("stop", generation, collected, uncollectable);
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001047 assert(!PyErr_Occurred());
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001048 return result;
1049}
1050
Neal Norwitz7b216c52006-03-04 20:01:53 +00001051static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001052collect_generations(void)
1053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 int i;
1055 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 /* Find the oldest generation (highest numbered) where the count
1058 * exceeds the threshold. Objects in the that generation and
1059 * generations younger than it will be collected. */
1060 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001061 if (_PyRuntime.gc.generations[i].count > _PyRuntime.gc.generations[i].threshold) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Avoid quadratic performance degradation in number
1063 of tracked objects. See comments at the beginning
1064 of this file, and issue #4074.
1065 */
1066 if (i == NUM_GENERATIONS - 1
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001067 && _PyRuntime.gc.long_lived_pending < _PyRuntime.gc.long_lived_total / 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 continue;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001069 n = collect_with_callback(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 break;
1071 }
1072 }
1073 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001074}
1075
Serhiy Storchaka93260282017-02-04 11:19:59 +02001076#include "clinic/gcmodule.c.h"
1077
1078/*[clinic input]
1079gc.enable
1080
1081Enable automatic garbage collection.
1082[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001083
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001084static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001085gc_enable_impl(PyObject *module)
1086/*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001087{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001088 _PyRuntime.gc.enabled = 1;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001089 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001090}
1091
Serhiy Storchaka93260282017-02-04 11:19:59 +02001092/*[clinic input]
1093gc.disable
1094
1095Disable automatic garbage collection.
1096[clinic start generated code]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001097
1098static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001099gc_disable_impl(PyObject *module)
1100/*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a14e800d83b]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001101{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001102 _PyRuntime.gc.enabled = 0;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001103 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001104}
1105
Serhiy Storchaka93260282017-02-04 11:19:59 +02001106/*[clinic input]
1107gc.isenabled -> bool
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001108
Serhiy Storchaka93260282017-02-04 11:19:59 +02001109Returns true if automatic garbage collection is enabled.
1110[clinic start generated code]*/
1111
1112static int
1113gc_isenabled_impl(PyObject *module)
1114/*[clinic end generated code: output=1874298331c49130 input=30005e0422373b31]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001115{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001116 return _PyRuntime.gc.enabled;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001117}
1118
Serhiy Storchaka93260282017-02-04 11:19:59 +02001119/*[clinic input]
1120gc.collect -> Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001121
Serhiy Storchaka93260282017-02-04 11:19:59 +02001122 generation: int(c_default="NUM_GENERATIONS - 1") = 2
1123
1124Run the garbage collector.
1125
1126With no arguments, run a full collection. The optional argument
1127may be an integer specifying which generation to collect. A ValueError
1128is raised if the generation number is invalid.
1129
1130The number of unreachable objects is returned.
1131[clinic start generated code]*/
1132
1133static Py_ssize_t
1134gc_collect_impl(PyObject *module, int generation)
1135/*[clinic end generated code: output=b697e633043233c7 input=40720128b682d879]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001138
Serhiy Storchaka93260282017-02-04 11:19:59 +02001139 if (generation < 0 || generation >= NUM_GENERATIONS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 PyErr_SetString(PyExc_ValueError, "invalid generation");
Serhiy Storchaka93260282017-02-04 11:19:59 +02001141 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 }
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001143
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001144 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 n = 0; /* already collecting, don't do anything */
1146 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001147 _PyRuntime.gc.collecting = 1;
Serhiy Storchaka93260282017-02-04 11:19:59 +02001148 n = collect_with_callback(generation);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001149 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001151
Serhiy Storchaka93260282017-02-04 11:19:59 +02001152 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001153}
1154
Serhiy Storchaka93260282017-02-04 11:19:59 +02001155/*[clinic input]
1156gc.set_debug
1157
1158 flags: int
1159 An integer that can have the following bits turned on:
1160 DEBUG_STATS - Print statistics during collection.
1161 DEBUG_COLLECTABLE - Print collectable objects found.
1162 DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
1163 found.
1164 DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
1165 DEBUG_LEAK - Debug leaking programs (everything but STATS).
1166 /
1167
1168Set the garbage collection debugging flags.
1169
1170Debugging information is written to sys.stderr.
1171[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001172
1173static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001174gc_set_debug_impl(PyObject *module, int flags)
1175/*[clinic end generated code: output=7c8366575486b228 input=5e5ce15e84fbed15]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001176{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001177 _PyRuntime.gc.debug = flags;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001178
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001179 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001180}
1181
Serhiy Storchaka93260282017-02-04 11:19:59 +02001182/*[clinic input]
1183gc.get_debug -> int
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001184
Serhiy Storchaka93260282017-02-04 11:19:59 +02001185Get the garbage collection debugging flags.
1186[clinic start generated code]*/
1187
1188static int
1189gc_get_debug_impl(PyObject *module)
1190/*[clinic end generated code: output=91242f3506cd1e50 input=91a101e1c3b98366]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001191{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001192 return _PyRuntime.gc.debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001193}
1194
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001195PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001196"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001197"\n"
1198"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001200
1201static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001202gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 int i;
1205 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001206 &_PyRuntime.gc.generations[0].threshold,
1207 &_PyRuntime.gc.generations[1].threshold,
1208 &_PyRuntime.gc.generations[2].threshold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 return NULL;
1210 for (i = 2; i < NUM_GENERATIONS; i++) {
1211 /* generations higher than 2 get the same threshold */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001212 _PyRuntime.gc.generations[i].threshold = _PyRuntime.gc.generations[2].threshold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001214
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001215 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001216}
1217
Serhiy Storchaka93260282017-02-04 11:19:59 +02001218/*[clinic input]
1219gc.get_threshold
1220
1221Return the current collection thresholds.
1222[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001223
1224static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001225gc_get_threshold_impl(PyObject *module)
1226/*[clinic end generated code: output=7902bc9f41ecbbd8 input=286d79918034d6e6]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001229 _PyRuntime.gc.generations[0].threshold,
1230 _PyRuntime.gc.generations[1].threshold,
1231 _PyRuntime.gc.generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001232}
1233
Serhiy Storchaka93260282017-02-04 11:19:59 +02001234/*[clinic input]
1235gc.get_count
1236
1237Return a three-tuple of the current collection counts.
1238[clinic start generated code]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001239
1240static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001241gc_get_count_impl(PyObject *module)
1242/*[clinic end generated code: output=354012e67b16398f input=a392794a08251751]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001245 _PyRuntime.gc.generations[0].count,
1246 _PyRuntime.gc.generations[1].count,
1247 _PyRuntime.gc.generations[2].count);
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001248}
1249
Neil Schemenauer48c70342001-08-09 15:38:31 +00001250static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001251referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 Py_ssize_t i;
1254 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1255 if (PyTuple_GET_ITEM(objs, i) == obj)
1256 return 1;
1257 return 0;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001258}
1259
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001260static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001261gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 PyGC_Head *gc;
1264 PyObject *obj;
1265 traverseproc traverse;
1266 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
1267 obj = FROM_GC(gc);
1268 traverse = Py_TYPE(obj)->tp_traverse;
1269 if (obj == objs || obj == resultlist)
1270 continue;
1271 if (traverse(obj, (visitproc)referrersvisit, objs)) {
1272 if (PyList_Append(resultlist, obj) < 0)
1273 return 0; /* error */
1274 }
1275 }
1276 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001277}
1278
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001279PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001280"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001281Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001282
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001283static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001284gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 int i;
1287 PyObject *result = PyList_New(0);
1288 if (!result) return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 for (i = 0; i < NUM_GENERATIONS; i++) {
1291 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1292 Py_DECREF(result);
1293 return NULL;
1294 }
1295 }
1296 return result;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001297}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001298
Tim Peters0f81ab62003-04-08 16:39:48 +00001299/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001300static int
Tim Peters730f5532003-04-08 17:17:17 +00001301referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001304}
1305
Tim Peters730f5532003-04-08 17:17:17 +00001306PyDoc_STRVAR(gc_get_referents__doc__,
1307"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001308Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001309
1310static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001311gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 Py_ssize_t i;
1314 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 if (result == NULL)
1317 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
1320 traverseproc traverse;
1321 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (! PyObject_IS_GC(obj))
1324 continue;
1325 traverse = Py_TYPE(obj)->tp_traverse;
1326 if (! traverse)
1327 continue;
1328 if (traverse(obj, (visitproc)referentsvisit, result)) {
1329 Py_DECREF(result);
1330 return NULL;
1331 }
1332 }
1333 return result;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001334}
1335
Serhiy Storchaka93260282017-02-04 11:19:59 +02001336/*[clinic input]
1337gc.get_objects
1338
1339Return a list of objects tracked by the collector (excluding the list returned).
1340[clinic start generated code]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001341
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001342static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001343gc_get_objects_impl(PyObject *module)
1344/*[clinic end generated code: output=fcb95d2e23e1f750 input=9439fe8170bf35d8]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 int i;
1347 PyObject* result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 result = PyList_New(0);
1350 if (result == NULL)
1351 return NULL;
1352 for (i = 0; i < NUM_GENERATIONS; i++) {
1353 if (append_objects(result, GEN_HEAD(i))) {
1354 Py_DECREF(result);
1355 return NULL;
1356 }
1357 }
1358 return result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001359}
1360
Serhiy Storchaka93260282017-02-04 11:19:59 +02001361/*[clinic input]
1362gc.get_stats
1363
1364Return a list of dictionaries containing per-generation statistics.
1365[clinic start generated code]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001366
1367static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001368gc_get_stats_impl(PyObject *module)
1369/*[clinic end generated code: output=a8ab1d8a5d26f3ab input=1ef4ed9d17b1a470]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001370{
1371 int i;
1372 PyObject *result;
1373 struct gc_generation_stats stats[NUM_GENERATIONS], *st;
1374
1375 /* To get consistent values despite allocations while constructing
1376 the result list, we use a snapshot of the running stats. */
1377 for (i = 0; i < NUM_GENERATIONS; i++) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001378 stats[i] = _PyRuntime.gc.generation_stats[i];
Antoine Pitroud4156c12012-10-30 22:43:19 +01001379 }
1380
1381 result = PyList_New(0);
1382 if (result == NULL)
1383 return NULL;
1384
1385 for (i = 0; i < NUM_GENERATIONS; i++) {
1386 PyObject *dict;
1387 st = &stats[i];
1388 dict = Py_BuildValue("{snsnsn}",
1389 "collections", st->collections,
1390 "collected", st->collected,
1391 "uncollectable", st->uncollectable
1392 );
1393 if (dict == NULL)
1394 goto error;
1395 if (PyList_Append(result, dict)) {
1396 Py_DECREF(dict);
1397 goto error;
1398 }
1399 Py_DECREF(dict);
1400 }
1401 return result;
1402
1403error:
1404 Py_XDECREF(result);
1405 return NULL;
1406}
1407
1408
Serhiy Storchaka93260282017-02-04 11:19:59 +02001409/*[clinic input]
1410gc.is_tracked
1411
1412 obj: object
1413 /
1414
1415Returns true if the object is tracked by the garbage collector.
1416
1417Simple atomic objects will return false.
1418[clinic start generated code]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001419
1420static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001421gc_is_tracked(PyObject *module, PyObject *obj)
1422/*[clinic end generated code: output=14f0103423b28e31 input=d83057f170ea2723]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PyObject *result;
1425
1426 if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
1427 result = Py_True;
1428 else
1429 result = Py_False;
1430 Py_INCREF(result);
1431 return result;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001432}
1433
brainfvckc75edab2017-10-16 12:49:41 -07001434/*[clinic input]
1435gc.freeze
1436
1437Freeze all current tracked objects and ignore them for future collections.
1438
1439This can be used before a POSIX fork() call to make the gc copy-on-write friendly.
1440Note: collection before a POSIX fork() call may free pages for future allocation
1441which can cause copy-on-write.
1442[clinic start generated code]*/
1443
1444static PyObject *
1445gc_freeze_impl(PyObject *module)
1446/*[clinic end generated code: output=502159d9cdc4c139 input=b602b16ac5febbe5]*/
1447{
1448 for (int i = 0; i < NUM_GENERATIONS; ++i) {
1449 gc_list_merge(GEN_HEAD(i), &_PyRuntime.gc.permanent_generation.head);
1450 _PyRuntime.gc.generations[i].count = 0;
1451 }
1452 Py_RETURN_NONE;
1453}
1454
1455/*[clinic input]
1456gc.unfreeze
1457
1458Unfreeze all objects in the permanent generation.
1459
1460Put all objects in the permanent generation back into oldest generation.
1461[clinic start generated code]*/
1462
1463static PyObject *
1464gc_unfreeze_impl(PyObject *module)
1465/*[clinic end generated code: output=1c15f2043b25e169 input=2dd52b170f4cef6c]*/
1466{
1467 gc_list_merge(&_PyRuntime.gc.permanent_generation.head, GEN_HEAD(NUM_GENERATIONS-1));
1468 Py_RETURN_NONE;
1469}
1470
1471/*[clinic input]
Victor Stinner05d68a82018-01-18 11:15:25 +01001472gc.get_freeze_count -> Py_ssize_t
brainfvckc75edab2017-10-16 12:49:41 -07001473
1474Return the number of objects in the permanent generation.
1475[clinic start generated code]*/
1476
Victor Stinner05d68a82018-01-18 11:15:25 +01001477static Py_ssize_t
brainfvckc75edab2017-10-16 12:49:41 -07001478gc_get_freeze_count_impl(PyObject *module)
Victor Stinner05d68a82018-01-18 11:15:25 +01001479/*[clinic end generated code: output=61cbd9f43aa032e1 input=45ffbc65cfe2a6ed]*/
brainfvckc75edab2017-10-16 12:49:41 -07001480{
1481 return gc_list_size(&_PyRuntime.gc.permanent_generation.head);
1482}
1483
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001485PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001486"This module provides access to the garbage collector for reference cycles.\n"
1487"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001488"enable() -- Enable automatic garbage collection.\n"
1489"disable() -- Disable automatic garbage collection.\n"
1490"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001491"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001492"get_count() -- Return the current collection counts.\n"
R David Murray0e814632013-12-26 15:11:28 -05001493"get_stats() -- Return list of dictionaries containing per-generation stats.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001494"set_debug() -- Set debugging flags.\n"
1495"get_debug() -- Get debugging flags.\n"
1496"set_threshold() -- Set the collection thresholds.\n"
1497"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001498"get_objects() -- Return a list of all objects tracked by the collector.\n"
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001499"is_tracked() -- Returns true if a given object is tracked.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001500"get_referrers() -- Return the list of objects that refer to an object.\n"
brainfvckc75edab2017-10-16 12:49:41 -07001501"get_referents() -- Return the list of objects that an object refers to.\n"
1502"freeze() -- Freeze all tracked objects and ignore them for future collections.\n"
1503"unfreeze() -- Unfreeze all objects in the permanent generation.\n"
1504"get_freeze_count() -- Return the number of objects in the permanent generation.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001505
1506static PyMethodDef GcMethods[] = {
Serhiy Storchaka93260282017-02-04 11:19:59 +02001507 GC_ENABLE_METHODDEF
1508 GC_DISABLE_METHODDEF
1509 GC_ISENABLED_METHODDEF
1510 GC_SET_DEBUG_METHODDEF
1511 GC_GET_DEBUG_METHODDEF
1512 GC_GET_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Serhiy Storchaka93260282017-02-04 11:19:59 +02001514 GC_GET_THRESHOLD_METHODDEF
1515 GC_COLLECT_METHODDEF
1516 GC_GET_OBJECTS_METHODDEF
1517 GC_GET_STATS_METHODDEF
1518 GC_IS_TRACKED_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 {"get_referrers", gc_get_referrers, METH_VARARGS,
1520 gc_get_referrers__doc__},
1521 {"get_referents", gc_get_referents, METH_VARARGS,
1522 gc_get_referents__doc__},
brainfvckc75edab2017-10-16 12:49:41 -07001523 GC_FREEZE_METHODDEF
1524 GC_UNFREEZE_METHODDEF
1525 GC_GET_FREEZE_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 {NULL, NULL} /* Sentinel */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001527};
1528
Martin v. Löwis1a214512008-06-11 05:26:20 +00001529static struct PyModuleDef gcmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 PyModuleDef_HEAD_INIT,
Antoine Pitrou696e0352010-08-08 22:18:46 +00001531 "gc", /* m_name */
1532 gc__doc__, /* m_doc */
1533 -1, /* m_size */
1534 GcMethods, /* m_methods */
1535 NULL, /* m_reload */
1536 NULL, /* m_traverse */
1537 NULL, /* m_clear */
1538 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001539};
1540
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001541PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001542PyInit_gc(void)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 m = PyModule_Create(&gcmodule);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (m == NULL)
1549 return NULL;
Tim Peters11558872003-04-06 23:30:52 +00001550
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001551 if (_PyRuntime.gc.garbage == NULL) {
1552 _PyRuntime.gc.garbage = PyList_New(0);
1553 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 return NULL;
1555 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001556 Py_INCREF(_PyRuntime.gc.garbage);
1557 if (PyModule_AddObject(m, "garbage", _PyRuntime.gc.garbage) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001559
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001560 if (_PyRuntime.gc.callbacks == NULL) {
1561 _PyRuntime.gc.callbacks = PyList_New(0);
1562 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001563 return NULL;
1564 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001565 Py_INCREF(_PyRuntime.gc.callbacks);
1566 if (PyModule_AddObject(m, "callbacks", _PyRuntime.gc.callbacks) < 0)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001567 return NULL;
1568
Martin v. Löwis1a214512008-06-11 05:26:20 +00001569#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 ADD_INT(DEBUG_STATS);
1571 ADD_INT(DEBUG_COLLECTABLE);
1572 ADD_INT(DEBUG_UNCOLLECTABLE);
1573 ADD_INT(DEBUG_SAVEALL);
1574 ADD_INT(DEBUG_LEAK);
Tim Peters11558872003-04-06 23:30:52 +00001575#undef ADD_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 return m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001577}
1578
Guido van Rossume13ddc92003-04-17 17:29:22 +00001579/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001580Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001581PyGC_Collect(void)
1582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001584
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001585 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 n = 0; /* already collecting, don't do anything */
1587 else {
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +03001588 PyObject *exc, *value, *tb;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001589 _PyRuntime.gc.collecting = 1;
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +03001590 PyErr_Fetch(&exc, &value, &tb);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001591 n = collect_with_callback(NUM_GENERATIONS - 1);
Serhiy Storchaka301e3cc2018-05-24 15:19:29 +03001592 PyErr_Restore(exc, value, tb);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001593 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 }
Guido van Rossume13ddc92003-04-17 17:29:22 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 return n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001597}
1598
Antoine Pitroufef34e32013-05-19 01:11:58 +02001599Py_ssize_t
Łukasz Langafef7e942016-09-09 21:47:46 -07001600_PyGC_CollectIfEnabled(void)
1601{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001602 if (!_PyRuntime.gc.enabled)
Łukasz Langafef7e942016-09-09 21:47:46 -07001603 return 0;
1604
1605 return PyGC_Collect();
1606}
1607
1608Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +02001609_PyGC_CollectNoFail(void)
1610{
1611 Py_ssize_t n;
1612
Serhiy Storchakac4653c92018-05-29 18:50:10 +03001613 assert(!PyErr_Occurred());
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001614 /* Ideally, this function is only called on interpreter shutdown,
1615 and therefore not recursively. Unfortunately, when there are daemon
1616 threads, a daemon thread can start a cyclic garbage collection
1617 during interpreter shutdown (and then never finish it).
1618 See http://bugs.python.org/issue8713#msg195178 for an example.
1619 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001620 if (_PyRuntime.gc.collecting)
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001621 n = 0;
1622 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001623 _PyRuntime.gc.collecting = 1;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001624 n = collect(NUM_GENERATIONS - 1, NULL, NULL, 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001625 _PyRuntime.gc.collecting = 0;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001626 }
Antoine Pitroufef34e32013-05-19 01:11:58 +02001627 return n;
1628}
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001629
Antoine Pitrou696e0352010-08-08 22:18:46 +00001630void
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001631_PyGC_DumpShutdownStats(void)
Antoine Pitrou696e0352010-08-08 22:18:46 +00001632{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001633 if (!(_PyRuntime.gc.debug & DEBUG_SAVEALL)
1634 && _PyRuntime.gc.garbage != NULL && PyList_GET_SIZE(_PyRuntime.gc.garbage) > 0) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001635 const char *message;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001636 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitroub5d82042010-11-05 00:05:25 +00001637 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001638 "shutdown";
1639 else
Antoine Pitroub5d82042010-11-05 00:05:25 +00001640 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001641 "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001642 /* PyErr_WarnFormat does too many things and we are at shutdown,
1643 the warnings module's dependencies (e.g. linecache) may be gone
1644 already. */
1645 if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1646 "gc", NULL, message,
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001647 PyList_GET_SIZE(_PyRuntime.gc.garbage)))
Georg Brandl08be72d2010-10-24 15:11:22 +00001648 PyErr_WriteUnraisable(NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001649 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE) {
Antoine Pitrou696e0352010-08-08 22:18:46 +00001650 PyObject *repr = NULL, *bytes = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001651 repr = PyObject_Repr(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001652 if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001653 PyErr_WriteUnraisable(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001654 else {
1655 PySys_WriteStderr(
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001656 " %s\n",
Antoine Pitrou696e0352010-08-08 22:18:46 +00001657 PyBytes_AS_STRING(bytes)
1658 );
1659 }
1660 Py_XDECREF(repr);
1661 Py_XDECREF(bytes);
1662 }
Antoine Pitrou696e0352010-08-08 22:18:46 +00001663 }
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001664}
1665
1666void
1667_PyGC_Fini(void)
1668{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001669 Py_CLEAR(_PyRuntime.gc.callbacks);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001670}
1671
Neil Schemenauer43411b52001-08-30 00:05:51 +00001672/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001673void
1674_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 _PyObject_Dump(FROM_GC(g));
Neil Schemenauer43411b52001-08-30 00:05:51 +00001677}
1678
Neil Schemenauer43411b52001-08-30 00:05:51 +00001679/* extension modules might be compiled with GC support so these
1680 functions must always be available */
1681
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001682#undef PyObject_GC_Track
1683#undef PyObject_GC_UnTrack
1684#undef PyObject_GC_Del
1685#undef _PyObject_GC_Malloc
1686
Neil Schemenauer43411b52001-08-30 00:05:51 +00001687void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001688PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 _PyObject_GC_TRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001691}
1692
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001693void
1694PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1697 * call PyObject_GC_UnTrack twice on an object.
1698 */
1699 if (IS_TRACKED(op))
1700 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001701}
1702
Victor Stinnerdb067af2014-05-02 22:31:14 +02001703static PyObject *
1704_PyObject_GC_Alloc(int use_calloc, size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyObject *op;
1707 PyGC_Head *g;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001708 size_t size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1710 return PyErr_NoMemory();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001711 size = sizeof(PyGC_Head) + basicsize;
1712 if (use_calloc)
1713 g = (PyGC_Head *)PyObject_Calloc(1, size);
1714 else
1715 g = (PyGC_Head *)PyObject_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (g == NULL)
1717 return PyErr_NoMemory();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001718 g->gc.gc_refs = 0;
1719 _PyGCHead_SET_REFS(g, GC_UNTRACKED);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001720 _PyRuntime.gc.generations[0].count++; /* number of allocated GC objects */
1721 if (_PyRuntime.gc.generations[0].count > _PyRuntime.gc.generations[0].threshold &&
1722 _PyRuntime.gc.enabled &&
1723 _PyRuntime.gc.generations[0].threshold &&
1724 !_PyRuntime.gc.collecting &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 !PyErr_Occurred()) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001726 _PyRuntime.gc.collecting = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 collect_generations();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001728 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 }
1730 op = FROM_GC(g);
1731 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001732}
1733
1734PyObject *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001735_PyObject_GC_Malloc(size_t basicsize)
1736{
1737 return _PyObject_GC_Alloc(0, basicsize);
1738}
1739
1740PyObject *
1741_PyObject_GC_Calloc(size_t basicsize)
1742{
1743 return _PyObject_GC_Alloc(1, basicsize);
1744}
1745
1746PyObject *
Neil Schemenauer43411b52001-08-30 00:05:51 +00001747_PyObject_GC_New(PyTypeObject *tp)
1748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
1750 if (op != NULL)
1751 op = PyObject_INIT(op, tp);
1752 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001753}
1754
1755PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001756_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001757{
Victor Stinner5d1866c2013-07-08 22:17:52 +02001758 size_t size;
1759 PyVarObject *op;
1760
1761 if (nitems < 0) {
1762 PyErr_BadInternalCall();
1763 return NULL;
1764 }
1765 size = _PyObject_VAR_SIZE(tp, nitems);
1766 op = (PyVarObject *) _PyObject_GC_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 if (op != NULL)
1768 op = PyObject_INIT_VAR(op, tp, nitems);
1769 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001770}
1771
1772PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001773_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
1776 PyGC_Head *g = AS_GC(op);
INADA Naoki1179f4b2018-05-21 18:35:41 +09001777 assert(!IS_TRACKED(op));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1779 return (PyVarObject *)PyErr_NoMemory();
1780 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
1781 if (g == NULL)
1782 return (PyVarObject *)PyErr_NoMemory();
1783 op = (PyVarObject *) FROM_GC(g);
1784 Py_SIZE(op) = nitems;
1785 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001786}
1787
1788void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001789PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 PyGC_Head *g = AS_GC(op);
1792 if (IS_TRACKED(op))
1793 gc_list_remove(g);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001794 if (_PyRuntime.gc.generations[0].count > 0) {
1795 _PyRuntime.gc.generations[0].count--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 }
1797 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001798}