blob: 8ba1093c029d1ab69085a3761daef8950884a7f9 [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 Peters259272b2003-04-06 19:41:39 +0000651 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
652 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000653 */
Tim Peters259272b2003-04-06 19:41:39 +0000654static int
Antoine Pitrou796564c2013-07-30 19:59:21 +0200655handle_legacy_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersf6b80452003-04-07 19:21:15 +0000658
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600659 if (_PyRuntime.gc.garbage == NULL) {
660 _PyRuntime.gc.garbage = PyList_New(0);
661 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 Py_FatalError("gc couldn't create gc.garbage list");
663 }
664 for (; gc != finalizers; gc = gc->gc.gc_next) {
665 PyObject *op = FROM_GC(gc);
Tim Petersf6b80452003-04-07 19:21:15 +0000666
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600667 if ((_PyRuntime.gc.debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {
668 if (PyList_Append(_PyRuntime.gc.garbage, op) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return -1;
670 }
671 }
Tim Petersf6b80452003-04-07 19:21:15 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 gc_list_merge(finalizers, old);
674 return 0;
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);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200707 Py_DECREF(op);
708 }
709 }
Tim Peters5fbc7b12014-05-08 17:42:19 -0500710 gc_list_merge(&seen, collectable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200711}
712
713/* Walk the collectable list and check that they are really unreachable
714 from the outside (some objects could have been resurrected by a
715 finalizer). */
716static int
717check_garbage(PyGC_Head *collectable)
718{
719 PyGC_Head *gc;
720 for (gc = collectable->gc.gc_next; gc != collectable;
721 gc = gc->gc.gc_next) {
722 _PyGCHead_SET_REFS(gc, Py_REFCNT(FROM_GC(gc)));
723 assert(_PyGCHead_REFS(gc) != 0);
724 }
725 subtract_refs(collectable);
726 for (gc = collectable->gc.gc_next; gc != collectable;
727 gc = gc->gc.gc_next) {
728 assert(_PyGCHead_REFS(gc) >= 0);
729 if (_PyGCHead_REFS(gc) != 0)
730 return -1;
731 }
732 return 0;
733}
734
735static void
736revive_garbage(PyGC_Head *collectable)
737{
738 PyGC_Head *gc;
739 for (gc = collectable->gc.gc_next; gc != collectable;
740 gc = gc->gc.gc_next) {
741 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
742 }
743}
744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000746 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000747 * objects may be freed. It is possible I screwed something up here.
748 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000749static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000750delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 inquiry clear;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 while (!gc_list_is_empty(collectable)) {
755 PyGC_Head *gc = collectable->gc.gc_next;
756 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000757
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600758 if (_PyRuntime.gc.debug & DEBUG_SAVEALL) {
759 PyList_Append(_PyRuntime.gc.garbage, op);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 }
761 else {
762 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
763 Py_INCREF(op);
764 clear(op);
765 Py_DECREF(op);
766 }
767 }
768 if (collectable->gc.gc_next == gc) {
769 /* object is still alive, move it, it may die later */
770 gc_list_move(gc, old);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200771 _PyGCHead_SET_REFS(gc, GC_REACHABLE);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 }
773 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000774}
775
Christian Heimesa156e092008-02-16 07:38:31 +0000776/* Clear all free lists
777 * All free lists are cleared during the collection of the highest generation.
778 * Allocated items in the free list may keep a pymalloc arena occupied.
779 * Clearing the free lists may give back memory to the OS earlier.
780 */
781static void
782clear_freelists(void)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 (void)PyMethod_ClearFreeList();
785 (void)PyFrame_ClearFreeList();
786 (void)PyCFunction_ClearFreeList();
787 (void)PyTuple_ClearFreeList();
788 (void)PyUnicode_ClearFreeList();
789 (void)PyFloat_ClearFreeList();
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100790 (void)PyList_ClearFreeList();
791 (void)PyDict_ClearFreeList();
Antoine Pitrou093ce9c2011-12-16 11:24:27 +0100792 (void)PySet_ClearFreeList();
Yury Selivanoveb636452016-09-08 22:01:51 -0700793 (void)PyAsyncGen_ClearFreeLists();
Yury Selivanovf23746a2018-01-22 19:11:18 -0500794 (void)PyContext_ClearFreeList();
Christian Heimesa156e092008-02-16 07:38:31 +0000795}
796
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000797/* This is the main function. Read this to understand how the
798 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000799static Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +0200800collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
801 int nofail)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 int i;
804 Py_ssize_t m = 0; /* # objects collected */
805 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
806 PyGC_Head *young; /* the generation we are examining */
807 PyGC_Head *old; /* next older generation */
808 PyGC_Head unreachable; /* non-problematic unreachable trash */
809 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
810 PyGC_Head *gc;
Victor Stinner7181dec2015-03-27 17:47:53 +0100811 _PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200812
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600813 struct gc_generation_stats *stats = &_PyRuntime.gc.generation_stats[generation];
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000814
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600815 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 PySys_WriteStderr("gc: collecting generation %d...\n",
817 generation);
818 PySys_WriteStderr("gc: objects in each generation:");
819 for (i = 0; i < NUM_GENERATIONS; i++)
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200820 PySys_FormatStderr(" %zd",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 gc_list_size(GEN_HEAD(i)));
brainfvckc75edab2017-10-16 12:49:41 -0700822 PySys_WriteStderr("\ngc: objects in permanent generation: %zd",
823 gc_list_size(&_PyRuntime.gc.permanent_generation.head));
Victor Stinner7181dec2015-03-27 17:47:53 +0100824 t1 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 PySys_WriteStderr("\n");
827 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000828
Łukasz Langaa785c872016-09-09 17:37:37 -0700829 if (PyDTrace_GC_START_ENABLED())
830 PyDTrace_GC_START(generation);
831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 /* update collection and allocation counters */
833 if (generation+1 < NUM_GENERATIONS)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600834 _PyRuntime.gc.generations[generation+1].count += 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 for (i = 0; i <= generation; i++)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600836 _PyRuntime.gc.generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* merge younger generations with one we are currently collecting */
839 for (i = 0; i < generation; i++) {
840 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
841 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* handy references */
844 young = GEN_HEAD(generation);
845 if (generation < NUM_GENERATIONS-1)
846 old = GEN_HEAD(generation+1);
847 else
848 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 /* Using ob_refcnt and gc_refs, calculate which objects in the
851 * container set are reachable from outside the set (i.e., have a
852 * refcount greater than 0 when all the references within the
853 * set are taken into account).
854 */
855 update_refs(young);
856 subtract_refs(young);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* Leave everything reachable from outside young in young, and move
859 * everything else (in young) to unreachable.
860 * NOTE: This used to move the reachable objects into a reachable
861 * set instead. But most things usually turn out to be reachable,
862 * so it's more efficient to move the unreachable things.
863 */
864 gc_list_init(&unreachable);
865 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 /* Move reachable objects to next generation. */
868 if (young != old) {
869 if (generation == NUM_GENERATIONS - 2) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 _PyRuntime.gc.long_lived_pending += gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 }
872 gc_list_merge(young, old);
873 }
874 else {
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200875 /* We only untrack dicts in full collections, to avoid quadratic
876 dict build-up. See issue #14775. */
877 untrack_dicts(young);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600878 _PyRuntime.gc.long_lived_pending = 0;
879 _PyRuntime.gc.long_lived_total = gc_list_size(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* All objects in unreachable are trash, but objects reachable from
Antoine Pitrou796564c2013-07-30 19:59:21 +0200883 * legacy finalizers (e.g. tp_del) can't safely be deleted.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 */
885 gc_list_init(&finalizers);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200886 move_legacy_finalizers(&unreachable, &finalizers);
887 /* finalizers contains the unreachable objects with a legacy finalizer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 * unreachable objects reachable *from* those are also uncollectable,
889 * and we move those into the finalizers list too.
890 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200891 move_legacy_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 /* Collect statistics on collectable objects found and print
894 * debugging information.
895 */
896 for (gc = unreachable.gc.gc_next; gc != &unreachable;
897 gc = gc->gc.gc_next) {
898 m++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600899 if (_PyRuntime.gc.debug & DEBUG_COLLECTABLE) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 debug_cycle("collectable", FROM_GC(gc));
901 }
902 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Clear weakrefs and invoke callbacks as necessary. */
905 m += handle_weakrefs(&unreachable, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000906
Antoine Pitrou796564c2013-07-30 19:59:21 +0200907 /* Call tp_finalize on objects which have one. */
Tim Peters5fbc7b12014-05-08 17:42:19 -0500908 finalize_garbage(&unreachable);
Antoine Pitrou796564c2013-07-30 19:59:21 +0200909
910 if (check_garbage(&unreachable)) {
911 revive_garbage(&unreachable);
912 gc_list_merge(&unreachable, old);
913 }
914 else {
915 /* Call tp_clear on objects in the unreachable set. This will cause
916 * the reference cycles to be broken. It may also cause some objects
917 * in finalizers to be freed.
918 */
919 delete_garbage(&unreachable, old);
920 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Collect statistics on uncollectable objects found and print
923 * debugging information. */
924 for (gc = finalizers.gc.gc_next;
925 gc != &finalizers;
926 gc = gc->gc.gc_next) {
927 n++;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600928 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 debug_cycle("uncollectable", FROM_GC(gc));
930 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600931 if (_PyRuntime.gc.debug & DEBUG_STATS) {
Victor Stinner7181dec2015-03-27 17:47:53 +0100932 _PyTime_t t2 = _PyTime_GetMonotonicClock();
Antoine Pitrou40f6b122014-05-24 19:21:53 +0200933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (m == 0 && n == 0)
935 PySys_WriteStderr("gc: done");
936 else
Antoine Pitrouded3c1b2014-05-24 19:24:40 +0200937 PySys_FormatStderr(
938 "gc: done, %zd unreachable, %zd uncollectable",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 n+m, n);
Victor Stinner7181dec2015-03-27 17:47:53 +0100940 PySys_WriteStderr(", %.4fs elapsed\n",
941 _PyTime_AsSecondsDouble(t2 - t1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 /* Append instances in the uncollectable set to a Python
945 * reachable list of garbage. The programmer has to deal with
946 * this if they insist on creating this type of structure.
947 */
Antoine Pitrou796564c2013-07-30 19:59:21 +0200948 (void)handle_legacy_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 /* Clear free list only during the collection of the highest
951 * generation */
952 if (generation == NUM_GENERATIONS-1) {
953 clear_freelists();
954 }
Christian Heimesa156e092008-02-16 07:38:31 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (PyErr_Occurred()) {
Antoine Pitroufef34e32013-05-19 01:11:58 +0200957 if (nofail) {
958 PyErr_Clear();
959 }
960 else {
961 if (gc_str == NULL)
962 gc_str = PyUnicode_FromString("garbage collection");
963 PyErr_WriteUnraisable(gc_str);
964 Py_FatalError("unexpected exception during garbage collection");
965 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000967
Antoine Pitroud4156c12012-10-30 22:43:19 +0100968 /* Update stats */
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000969 if (n_collected)
970 *n_collected = m;
971 if (n_uncollectable)
972 *n_uncollectable = n;
Antoine Pitroud4156c12012-10-30 22:43:19 +0100973 stats->collections++;
974 stats->collected += m;
975 stats->uncollectable += n;
Łukasz Langaa785c872016-09-09 17:37:37 -0700976
977 if (PyDTrace_GC_DONE_ENABLED())
978 PyDTrace_GC_DONE(n+m);
979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return n+m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000981}
982
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000983/* Invoke progress callbacks to notify clients that garbage collection
984 * is starting or stopping
985 */
986static void
987invoke_gc_callback(const char *phase, int generation,
988 Py_ssize_t collected, Py_ssize_t uncollectable)
989{
990 Py_ssize_t i;
991 PyObject *info = NULL;
992
993 /* we may get called very early */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600994 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000995 return;
996 /* The local variable cannot be rebound, check it for sanity */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600997 assert(_PyRuntime.gc.callbacks != NULL && PyList_CheckExact(_PyRuntime.gc.callbacks));
998 if (PyList_GET_SIZE(_PyRuntime.gc.callbacks) != 0) {
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +0000999 info = Py_BuildValue("{sisnsn}",
1000 "generation", generation,
1001 "collected", collected,
1002 "uncollectable", uncollectable);
1003 if (info == NULL) {
1004 PyErr_WriteUnraisable(NULL);
1005 return;
1006 }
1007 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001008 for (i=0; i<PyList_GET_SIZE(_PyRuntime.gc.callbacks); i++) {
1009 PyObject *r, *cb = PyList_GET_ITEM(_PyRuntime.gc.callbacks, i);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001010 Py_INCREF(cb); /* make sure cb doesn't go away */
1011 r = PyObject_CallFunction(cb, "sO", phase, info);
1012 Py_XDECREF(r);
1013 if (r == NULL)
1014 PyErr_WriteUnraisable(cb);
1015 Py_DECREF(cb);
1016 }
1017 Py_XDECREF(info);
1018}
1019
1020/* Perform garbage collection of a generation and invoke
1021 * progress callbacks.
1022 */
1023static Py_ssize_t
1024collect_with_callback(int generation)
1025{
1026 Py_ssize_t result, collected, uncollectable;
1027 invoke_gc_callback("start", generation, 0, 0);
Antoine Pitroufef34e32013-05-19 01:11:58 +02001028 result = collect(generation, &collected, &uncollectable, 0);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001029 invoke_gc_callback("stop", generation, collected, uncollectable);
1030 return result;
1031}
1032
Neal Norwitz7b216c52006-03-04 20:01:53 +00001033static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001034collect_generations(void)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 int i;
1037 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* Find the oldest generation (highest numbered) where the count
1040 * exceeds the threshold. Objects in the that generation and
1041 * generations younger than it will be collected. */
1042 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001043 if (_PyRuntime.gc.generations[i].count > _PyRuntime.gc.generations[i].threshold) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 /* Avoid quadratic performance degradation in number
1045 of tracked objects. See comments at the beginning
1046 of this file, and issue #4074.
1047 */
1048 if (i == NUM_GENERATIONS - 1
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 && _PyRuntime.gc.long_lived_pending < _PyRuntime.gc.long_lived_total / 4)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 continue;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001051 n = collect_with_callback(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 break;
1053 }
1054 }
1055 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001056}
1057
Serhiy Storchaka93260282017-02-04 11:19:59 +02001058#include "clinic/gcmodule.c.h"
1059
1060/*[clinic input]
1061gc.enable
1062
1063Enable automatic garbage collection.
1064[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001065
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001066static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001067gc_enable_impl(PyObject *module)
1068/*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001069{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001070 _PyRuntime.gc.enabled = 1;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001071 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001072}
1073
Serhiy Storchaka93260282017-02-04 11:19:59 +02001074/*[clinic input]
1075gc.disable
1076
1077Disable automatic garbage collection.
1078[clinic start generated code]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001079
1080static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001081gc_disable_impl(PyObject *module)
1082/*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a14e800d83b]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001083{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001084 _PyRuntime.gc.enabled = 0;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001085 Py_RETURN_NONE;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001086}
1087
Serhiy Storchaka93260282017-02-04 11:19:59 +02001088/*[clinic input]
1089gc.isenabled -> bool
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001090
Serhiy Storchaka93260282017-02-04 11:19:59 +02001091Returns true if automatic garbage collection is enabled.
1092[clinic start generated code]*/
1093
1094static int
1095gc_isenabled_impl(PyObject *module)
1096/*[clinic end generated code: output=1874298331c49130 input=30005e0422373b31]*/
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001097{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001098 return _PyRuntime.gc.enabled;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001099}
1100
Serhiy Storchaka93260282017-02-04 11:19:59 +02001101/*[clinic input]
1102gc.collect -> Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001103
Serhiy Storchaka93260282017-02-04 11:19:59 +02001104 generation: int(c_default="NUM_GENERATIONS - 1") = 2
1105
1106Run the garbage collector.
1107
1108With no arguments, run a full collection. The optional argument
1109may be an integer specifying which generation to collect. A ValueError
1110is raised if the generation number is invalid.
1111
1112The number of unreachable objects is returned.
1113[clinic start generated code]*/
1114
1115static Py_ssize_t
1116gc_collect_impl(PyObject *module, int generation)
1117/*[clinic end generated code: output=b697e633043233c7 input=40720128b682d879]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001120
Serhiy Storchaka93260282017-02-04 11:19:59 +02001121 if (generation < 0 || generation >= NUM_GENERATIONS) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyErr_SetString(PyExc_ValueError, "invalid generation");
Serhiy Storchaka93260282017-02-04 11:19:59 +02001123 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 }
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001125
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001126 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 n = 0; /* already collecting, don't do anything */
1128 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001129 _PyRuntime.gc.collecting = 1;
Serhiy Storchaka93260282017-02-04 11:19:59 +02001130 n = collect_with_callback(generation);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001131 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001133
Serhiy Storchaka93260282017-02-04 11:19:59 +02001134 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001135}
1136
Serhiy Storchaka93260282017-02-04 11:19:59 +02001137/*[clinic input]
1138gc.set_debug
1139
1140 flags: int
1141 An integer that can have the following bits turned on:
1142 DEBUG_STATS - Print statistics during collection.
1143 DEBUG_COLLECTABLE - Print collectable objects found.
1144 DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
1145 found.
1146 DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
1147 DEBUG_LEAK - Debug leaking programs (everything but STATS).
1148 /
1149
1150Set the garbage collection debugging flags.
1151
1152Debugging information is written to sys.stderr.
1153[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001154
1155static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001156gc_set_debug_impl(PyObject *module, int flags)
1157/*[clinic end generated code: output=7c8366575486b228 input=5e5ce15e84fbed15]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001159 _PyRuntime.gc.debug = flags;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001160
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001161 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001162}
1163
Serhiy Storchaka93260282017-02-04 11:19:59 +02001164/*[clinic input]
1165gc.get_debug -> int
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001166
Serhiy Storchaka93260282017-02-04 11:19:59 +02001167Get the garbage collection debugging flags.
1168[clinic start generated code]*/
1169
1170static int
1171gc_get_debug_impl(PyObject *module)
1172/*[clinic end generated code: output=91242f3506cd1e50 input=91a101e1c3b98366]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001173{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001174 return _PyRuntime.gc.debug;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001175}
1176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001177PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001178"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001179"\n"
1180"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001181"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001182
1183static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001184gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 int i;
1187 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001188 &_PyRuntime.gc.generations[0].threshold,
1189 &_PyRuntime.gc.generations[1].threshold,
1190 &_PyRuntime.gc.generations[2].threshold))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 return NULL;
1192 for (i = 2; i < NUM_GENERATIONS; i++) {
1193 /* generations higher than 2 get the same threshold */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001194 _PyRuntime.gc.generations[i].threshold = _PyRuntime.gc.generations[2].threshold;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001196
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001197 Py_RETURN_NONE;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001198}
1199
Serhiy Storchaka93260282017-02-04 11:19:59 +02001200/*[clinic input]
1201gc.get_threshold
1202
1203Return the current collection thresholds.
1204[clinic start generated code]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001205
1206static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001207gc_get_threshold_impl(PyObject *module)
1208/*[clinic end generated code: output=7902bc9f41ecbbd8 input=286d79918034d6e6]*/
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001211 _PyRuntime.gc.generations[0].threshold,
1212 _PyRuntime.gc.generations[1].threshold,
1213 _PyRuntime.gc.generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001214}
1215
Serhiy Storchaka93260282017-02-04 11:19:59 +02001216/*[clinic input]
1217gc.get_count
1218
1219Return a three-tuple of the current collection counts.
1220[clinic start generated code]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001221
1222static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001223gc_get_count_impl(PyObject *module)
1224/*[clinic end generated code: output=354012e67b16398f input=a392794a08251751]*/
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return Py_BuildValue("(iii)",
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001227 _PyRuntime.gc.generations[0].count,
1228 _PyRuntime.gc.generations[1].count,
1229 _PyRuntime.gc.generations[2].count);
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001230}
1231
Neil Schemenauer48c70342001-08-09 15:38:31 +00001232static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001233referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 Py_ssize_t i;
1236 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1237 if (PyTuple_GET_ITEM(objs, i) == obj)
1238 return 1;
1239 return 0;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001240}
1241
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001242static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001243gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyGC_Head *gc;
1246 PyObject *obj;
1247 traverseproc traverse;
1248 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
1249 obj = FROM_GC(gc);
1250 traverse = Py_TYPE(obj)->tp_traverse;
1251 if (obj == objs || obj == resultlist)
1252 continue;
1253 if (traverse(obj, (visitproc)referrersvisit, objs)) {
1254 if (PyList_Append(resultlist, obj) < 0)
1255 return 0; /* error */
1256 }
1257 }
1258 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001259}
1260
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001261PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001262"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001263Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001264
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001265static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001266gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 int i;
1269 PyObject *result = PyList_New(0);
1270 if (!result) return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 for (i = 0; i < NUM_GENERATIONS; i++) {
1273 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1274 Py_DECREF(result);
1275 return NULL;
1276 }
1277 }
1278 return result;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001279}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001280
Tim Peters0f81ab62003-04-08 16:39:48 +00001281/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001282static int
Tim Peters730f5532003-04-08 17:17:17 +00001283referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001286}
1287
Tim Peters730f5532003-04-08 17:17:17 +00001288PyDoc_STRVAR(gc_get_referents__doc__,
1289"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001290Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001291
1292static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001293gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 Py_ssize_t i;
1296 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (result == NULL)
1299 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
1302 traverseproc traverse;
1303 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (! PyObject_IS_GC(obj))
1306 continue;
1307 traverse = Py_TYPE(obj)->tp_traverse;
1308 if (! traverse)
1309 continue;
1310 if (traverse(obj, (visitproc)referentsvisit, result)) {
1311 Py_DECREF(result);
1312 return NULL;
1313 }
1314 }
1315 return result;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001316}
1317
Serhiy Storchaka93260282017-02-04 11:19:59 +02001318/*[clinic input]
1319gc.get_objects
1320
1321Return a list of objects tracked by the collector (excluding the list returned).
1322[clinic start generated code]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001323
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001324static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001325gc_get_objects_impl(PyObject *module)
1326/*[clinic end generated code: output=fcb95d2e23e1f750 input=9439fe8170bf35d8]*/
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 int i;
1329 PyObject* result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 result = PyList_New(0);
1332 if (result == NULL)
1333 return NULL;
1334 for (i = 0; i < NUM_GENERATIONS; i++) {
1335 if (append_objects(result, GEN_HEAD(i))) {
1336 Py_DECREF(result);
1337 return NULL;
1338 }
1339 }
1340 return result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001341}
1342
Serhiy Storchaka93260282017-02-04 11:19:59 +02001343/*[clinic input]
1344gc.get_stats
1345
1346Return a list of dictionaries containing per-generation statistics.
1347[clinic start generated code]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001348
1349static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001350gc_get_stats_impl(PyObject *module)
1351/*[clinic end generated code: output=a8ab1d8a5d26f3ab input=1ef4ed9d17b1a470]*/
Antoine Pitroud4156c12012-10-30 22:43:19 +01001352{
1353 int i;
1354 PyObject *result;
1355 struct gc_generation_stats stats[NUM_GENERATIONS], *st;
1356
1357 /* To get consistent values despite allocations while constructing
1358 the result list, we use a snapshot of the running stats. */
1359 for (i = 0; i < NUM_GENERATIONS; i++) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001360 stats[i] = _PyRuntime.gc.generation_stats[i];
Antoine Pitroud4156c12012-10-30 22:43:19 +01001361 }
1362
1363 result = PyList_New(0);
1364 if (result == NULL)
1365 return NULL;
1366
1367 for (i = 0; i < NUM_GENERATIONS; i++) {
1368 PyObject *dict;
1369 st = &stats[i];
1370 dict = Py_BuildValue("{snsnsn}",
1371 "collections", st->collections,
1372 "collected", st->collected,
1373 "uncollectable", st->uncollectable
1374 );
1375 if (dict == NULL)
1376 goto error;
1377 if (PyList_Append(result, dict)) {
1378 Py_DECREF(dict);
1379 goto error;
1380 }
1381 Py_DECREF(dict);
1382 }
1383 return result;
1384
1385error:
1386 Py_XDECREF(result);
1387 return NULL;
1388}
1389
1390
Serhiy Storchaka93260282017-02-04 11:19:59 +02001391/*[clinic input]
1392gc.is_tracked
1393
1394 obj: object
1395 /
1396
1397Returns true if the object is tracked by the garbage collector.
1398
1399Simple atomic objects will return false.
1400[clinic start generated code]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001401
1402static PyObject *
Serhiy Storchaka93260282017-02-04 11:19:59 +02001403gc_is_tracked(PyObject *module, PyObject *obj)
1404/*[clinic end generated code: output=14f0103423b28e31 input=d83057f170ea2723]*/
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyObject *result;
1407
1408 if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
1409 result = Py_True;
1410 else
1411 result = Py_False;
1412 Py_INCREF(result);
1413 return result;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001414}
1415
brainfvckc75edab2017-10-16 12:49:41 -07001416/*[clinic input]
1417gc.freeze
1418
1419Freeze all current tracked objects and ignore them for future collections.
1420
1421This can be used before a POSIX fork() call to make the gc copy-on-write friendly.
1422Note: collection before a POSIX fork() call may free pages for future allocation
1423which can cause copy-on-write.
1424[clinic start generated code]*/
1425
1426static PyObject *
1427gc_freeze_impl(PyObject *module)
1428/*[clinic end generated code: output=502159d9cdc4c139 input=b602b16ac5febbe5]*/
1429{
1430 for (int i = 0; i < NUM_GENERATIONS; ++i) {
1431 gc_list_merge(GEN_HEAD(i), &_PyRuntime.gc.permanent_generation.head);
1432 _PyRuntime.gc.generations[i].count = 0;
1433 }
1434 Py_RETURN_NONE;
1435}
1436
1437/*[clinic input]
1438gc.unfreeze
1439
1440Unfreeze all objects in the permanent generation.
1441
1442Put all objects in the permanent generation back into oldest generation.
1443[clinic start generated code]*/
1444
1445static PyObject *
1446gc_unfreeze_impl(PyObject *module)
1447/*[clinic end generated code: output=1c15f2043b25e169 input=2dd52b170f4cef6c]*/
1448{
1449 gc_list_merge(&_PyRuntime.gc.permanent_generation.head, GEN_HEAD(NUM_GENERATIONS-1));
1450 Py_RETURN_NONE;
1451}
1452
1453/*[clinic input]
Victor Stinner05d68a82018-01-18 11:15:25 +01001454gc.get_freeze_count -> Py_ssize_t
brainfvckc75edab2017-10-16 12:49:41 -07001455
1456Return the number of objects in the permanent generation.
1457[clinic start generated code]*/
1458
Victor Stinner05d68a82018-01-18 11:15:25 +01001459static Py_ssize_t
brainfvckc75edab2017-10-16 12:49:41 -07001460gc_get_freeze_count_impl(PyObject *module)
Victor Stinner05d68a82018-01-18 11:15:25 +01001461/*[clinic end generated code: output=61cbd9f43aa032e1 input=45ffbc65cfe2a6ed]*/
brainfvckc75edab2017-10-16 12:49:41 -07001462{
1463 return gc_list_size(&_PyRuntime.gc.permanent_generation.head);
1464}
1465
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001467PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001468"This module provides access to the garbage collector for reference cycles.\n"
1469"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001470"enable() -- Enable automatic garbage collection.\n"
1471"disable() -- Disable automatic garbage collection.\n"
1472"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001473"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001474"get_count() -- Return the current collection counts.\n"
R David Murray0e814632013-12-26 15:11:28 -05001475"get_stats() -- Return list of dictionaries containing per-generation stats.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001476"set_debug() -- Set debugging flags.\n"
1477"get_debug() -- Get debugging flags.\n"
1478"set_threshold() -- Set the collection thresholds.\n"
1479"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001480"get_objects() -- Return a list of all objects tracked by the collector.\n"
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001481"is_tracked() -- Returns true if a given object is tracked.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001482"get_referrers() -- Return the list of objects that refer to an object.\n"
brainfvckc75edab2017-10-16 12:49:41 -07001483"get_referents() -- Return the list of objects that an object refers to.\n"
1484"freeze() -- Freeze all tracked objects and ignore them for future collections.\n"
1485"unfreeze() -- Unfreeze all objects in the permanent generation.\n"
1486"get_freeze_count() -- Return the number of objects in the permanent generation.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001487
1488static PyMethodDef GcMethods[] = {
Serhiy Storchaka93260282017-02-04 11:19:59 +02001489 GC_ENABLE_METHODDEF
1490 GC_DISABLE_METHODDEF
1491 GC_ISENABLED_METHODDEF
1492 GC_SET_DEBUG_METHODDEF
1493 GC_GET_DEBUG_METHODDEF
1494 GC_GET_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
Serhiy Storchaka93260282017-02-04 11:19:59 +02001496 GC_GET_THRESHOLD_METHODDEF
1497 GC_COLLECT_METHODDEF
1498 GC_GET_OBJECTS_METHODDEF
1499 GC_GET_STATS_METHODDEF
1500 GC_IS_TRACKED_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 {"get_referrers", gc_get_referrers, METH_VARARGS,
1502 gc_get_referrers__doc__},
1503 {"get_referents", gc_get_referents, METH_VARARGS,
1504 gc_get_referents__doc__},
brainfvckc75edab2017-10-16 12:49:41 -07001505 GC_FREEZE_METHODDEF
1506 GC_UNFREEZE_METHODDEF
1507 GC_GET_FREEZE_COUNT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 {NULL, NULL} /* Sentinel */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001509};
1510
Martin v. Löwis1a214512008-06-11 05:26:20 +00001511static struct PyModuleDef gcmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyModuleDef_HEAD_INIT,
Antoine Pitrou696e0352010-08-08 22:18:46 +00001513 "gc", /* m_name */
1514 gc__doc__, /* m_doc */
1515 -1, /* m_size */
1516 GcMethods, /* m_methods */
1517 NULL, /* m_reload */
1518 NULL, /* m_traverse */
1519 NULL, /* m_clear */
1520 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001521};
1522
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001523PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001524PyInit_gc(void)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 m = PyModule_Create(&gcmodule);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 if (m == NULL)
1531 return NULL;
Tim Peters11558872003-04-06 23:30:52 +00001532
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001533 if (_PyRuntime.gc.garbage == NULL) {
1534 _PyRuntime.gc.garbage = PyList_New(0);
1535 if (_PyRuntime.gc.garbage == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 return NULL;
1537 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001538 Py_INCREF(_PyRuntime.gc.garbage);
1539 if (PyModule_AddObject(m, "garbage", _PyRuntime.gc.garbage) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001542 if (_PyRuntime.gc.callbacks == NULL) {
1543 _PyRuntime.gc.callbacks = PyList_New(0);
1544 if (_PyRuntime.gc.callbacks == NULL)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001545 return NULL;
1546 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001547 Py_INCREF(_PyRuntime.gc.callbacks);
1548 if (PyModule_AddObject(m, "callbacks", _PyRuntime.gc.callbacks) < 0)
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001549 return NULL;
1550
Martin v. Löwis1a214512008-06-11 05:26:20 +00001551#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 ADD_INT(DEBUG_STATS);
1553 ADD_INT(DEBUG_COLLECTABLE);
1554 ADD_INT(DEBUG_UNCOLLECTABLE);
1555 ADD_INT(DEBUG_SAVEALL);
1556 ADD_INT(DEBUG_LEAK);
Tim Peters11558872003-04-06 23:30:52 +00001557#undef ADD_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001559}
1560
Guido van Rossume13ddc92003-04-17 17:29:22 +00001561/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001562Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001563PyGC_Collect(void)
1564{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001566
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001567 if (_PyRuntime.gc.collecting)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 n = 0; /* already collecting, don't do anything */
1569 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001570 _PyRuntime.gc.collecting = 1;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001571 n = collect_with_callback(NUM_GENERATIONS - 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001572 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
Guido van Rossume13ddc92003-04-17 17:29:22 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 return n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001576}
1577
Antoine Pitroufef34e32013-05-19 01:11:58 +02001578Py_ssize_t
Łukasz Langafef7e942016-09-09 21:47:46 -07001579_PyGC_CollectIfEnabled(void)
1580{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001581 if (!_PyRuntime.gc.enabled)
Łukasz Langafef7e942016-09-09 21:47:46 -07001582 return 0;
1583
1584 return PyGC_Collect();
1585}
1586
1587Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +02001588_PyGC_CollectNoFail(void)
1589{
1590 Py_ssize_t n;
1591
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001592 /* Ideally, this function is only called on interpreter shutdown,
1593 and therefore not recursively. Unfortunately, when there are daemon
1594 threads, a daemon thread can start a cyclic garbage collection
1595 during interpreter shutdown (and then never finish it).
1596 See http://bugs.python.org/issue8713#msg195178 for an example.
1597 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001598 if (_PyRuntime.gc.collecting)
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001599 n = 0;
1600 else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001601 _PyRuntime.gc.collecting = 1;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001602 n = collect(NUM_GENERATIONS - 1, NULL, NULL, 1);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001603 _PyRuntime.gc.collecting = 0;
Antoine Pitrouc69c9bc2013-08-15 20:15:15 +02001604 }
Antoine Pitroufef34e32013-05-19 01:11:58 +02001605 return n;
1606}
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001607
Antoine Pitrou696e0352010-08-08 22:18:46 +00001608void
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001609_PyGC_DumpShutdownStats(void)
Antoine Pitrou696e0352010-08-08 22:18:46 +00001610{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001611 if (!(_PyRuntime.gc.debug & DEBUG_SAVEALL)
1612 && _PyRuntime.gc.garbage != NULL && PyList_GET_SIZE(_PyRuntime.gc.garbage) > 0) {
Serhiy Storchakae2f92de2017-11-11 13:06:26 +02001613 const char *message;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001614 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE)
Antoine Pitroub5d82042010-11-05 00:05:25 +00001615 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001616 "shutdown";
1617 else
Antoine Pitroub5d82042010-11-05 00:05:25 +00001618 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001619 "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001620 /* PyErr_WarnFormat does too many things and we are at shutdown,
1621 the warnings module's dependencies (e.g. linecache) may be gone
1622 already. */
1623 if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1624 "gc", NULL, message,
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001625 PyList_GET_SIZE(_PyRuntime.gc.garbage)))
Georg Brandl08be72d2010-10-24 15:11:22 +00001626 PyErr_WriteUnraisable(NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001627 if (_PyRuntime.gc.debug & DEBUG_UNCOLLECTABLE) {
Antoine Pitrou696e0352010-08-08 22:18:46 +00001628 PyObject *repr = NULL, *bytes = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001629 repr = PyObject_Repr(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001630 if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001631 PyErr_WriteUnraisable(_PyRuntime.gc.garbage);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001632 else {
1633 PySys_WriteStderr(
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001634 " %s\n",
Antoine Pitrou696e0352010-08-08 22:18:46 +00001635 PyBytes_AS_STRING(bytes)
1636 );
1637 }
1638 Py_XDECREF(repr);
1639 Py_XDECREF(bytes);
1640 }
Antoine Pitrou696e0352010-08-08 22:18:46 +00001641 }
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001642}
1643
1644void
1645_PyGC_Fini(void)
1646{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001647 Py_CLEAR(_PyRuntime.gc.callbacks);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001648}
1649
Neil Schemenauer43411b52001-08-30 00:05:51 +00001650/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001651void
1652_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 _PyObject_Dump(FROM_GC(g));
Neil Schemenauer43411b52001-08-30 00:05:51 +00001655}
1656
Neil Schemenauer43411b52001-08-30 00:05:51 +00001657/* extension modules might be compiled with GC support so these
1658 functions must always be available */
1659
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001660#undef PyObject_GC_Track
1661#undef PyObject_GC_UnTrack
1662#undef PyObject_GC_Del
1663#undef _PyObject_GC_Malloc
1664
Neil Schemenauer43411b52001-08-30 00:05:51 +00001665void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001666PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 _PyObject_GC_TRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001669}
1670
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001671void
1672PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1675 * call PyObject_GC_UnTrack twice on an object.
1676 */
1677 if (IS_TRACKED(op))
1678 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001679}
1680
Victor Stinnerdb067af2014-05-02 22:31:14 +02001681static PyObject *
1682_PyObject_GC_Alloc(int use_calloc, size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001683{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 PyObject *op;
1685 PyGC_Head *g;
Victor Stinnerdb067af2014-05-02 22:31:14 +02001686 size_t size;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1688 return PyErr_NoMemory();
Victor Stinnerdb067af2014-05-02 22:31:14 +02001689 size = sizeof(PyGC_Head) + basicsize;
1690 if (use_calloc)
1691 g = (PyGC_Head *)PyObject_Calloc(1, size);
1692 else
1693 g = (PyGC_Head *)PyObject_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (g == NULL)
1695 return PyErr_NoMemory();
Antoine Pitrou796564c2013-07-30 19:59:21 +02001696 g->gc.gc_refs = 0;
1697 _PyGCHead_SET_REFS(g, GC_UNTRACKED);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001698 _PyRuntime.gc.generations[0].count++; /* number of allocated GC objects */
1699 if (_PyRuntime.gc.generations[0].count > _PyRuntime.gc.generations[0].threshold &&
1700 _PyRuntime.gc.enabled &&
1701 _PyRuntime.gc.generations[0].threshold &&
1702 !_PyRuntime.gc.collecting &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001703 !PyErr_Occurred()) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001704 _PyRuntime.gc.collecting = 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 collect_generations();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001706 _PyRuntime.gc.collecting = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 }
1708 op = FROM_GC(g);
1709 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001710}
1711
1712PyObject *
Victor Stinnerdb067af2014-05-02 22:31:14 +02001713_PyObject_GC_Malloc(size_t basicsize)
1714{
1715 return _PyObject_GC_Alloc(0, basicsize);
1716}
1717
1718PyObject *
1719_PyObject_GC_Calloc(size_t basicsize)
1720{
1721 return _PyObject_GC_Alloc(1, basicsize);
1722}
1723
1724PyObject *
Neil Schemenauer43411b52001-08-30 00:05:51 +00001725_PyObject_GC_New(PyTypeObject *tp)
1726{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
1728 if (op != NULL)
1729 op = PyObject_INIT(op, tp);
1730 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001731}
1732
1733PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001734_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001735{
Victor Stinner5d1866c2013-07-08 22:17:52 +02001736 size_t size;
1737 PyVarObject *op;
1738
1739 if (nitems < 0) {
1740 PyErr_BadInternalCall();
1741 return NULL;
1742 }
1743 size = _PyObject_VAR_SIZE(tp, nitems);
1744 op = (PyVarObject *) _PyObject_GC_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 if (op != NULL)
1746 op = PyObject_INIT_VAR(op, tp, nitems);
1747 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001748}
1749
1750PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001751_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
1754 PyGC_Head *g = AS_GC(op);
1755 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1756 return (PyVarObject *)PyErr_NoMemory();
1757 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
1758 if (g == NULL)
1759 return (PyVarObject *)PyErr_NoMemory();
1760 op = (PyVarObject *) FROM_GC(g);
1761 Py_SIZE(op) = nitems;
1762 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001763}
1764
1765void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001766PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 PyGC_Head *g = AS_GC(op);
1769 if (IS_TRACKED(op))
1770 gc_list_remove(g);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001771 if (_PyRuntime.gc.generations[0].count > 0) {
1772 _PyRuntime.gc.generations[0].count--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 }
1774 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001775}