blob: d96d2c7b68a70e31f84ef53abcd1d300fd21683a [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"
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000027#include "frameobject.h" /* for PyFrame_ClearFreeList */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000028
Neil Schemenauer43411b52001-08-30 00:05:51 +000029/* Get an object's GC head */
30#define AS_GC(o) ((PyGC_Head *)(o)-1)
31
32/* Get the object given the GC head */
33#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
34
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000035/*** Global GC state ***/
36
Neil Schemenauer2880ae52002-05-04 05:35:20 +000037struct gc_generation {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000038 PyGC_Head head;
39 int threshold; /* collection threshold */
40 int count; /* count of allocations or collections of younger
41 generations */
Neil Schemenauer2880ae52002-05-04 05:35:20 +000042};
43
44#define NUM_GENERATIONS 3
45#define GEN_HEAD(n) (&generations[n].head)
46
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000047/* linked lists of container objects */
Neil Schemenauer2880ae52002-05-04 05:35:20 +000048static struct gc_generation generations[NUM_GENERATIONS] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000049 /* PyGC_Head, threshold, count */
50 {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
51 {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
52 {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
Neil Schemenauer2880ae52002-05-04 05:35:20 +000053};
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000054
Neil Schemenauer2880ae52002-05-04 05:35:20 +000055PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);
56
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +000057static int enabled = 1; /* automatic collection enabled? */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +000058
Neil Schemenauer43411b52001-08-30 00:05:51 +000059/* true if we are currently running the collector */
Tim Petersbf384c22003-04-06 00:11:39 +000060static int collecting = 0;
Neil Schemenauer43411b52001-08-30 00:05:51 +000061
Tim Peters6fc13d92002-07-02 18:12:35 +000062/* list of uncollectable objects */
Tim Petersbf384c22003-04-06 00:11:39 +000063static PyObject *garbage = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000064
65/* Python string to use if unhandled exception occurs */
Tim Petersbf384c22003-04-06 00:11:39 +000066static PyObject *gc_str = NULL;
Tim Peters6fc13d92002-07-02 18:12:35 +000067
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +000068/* a list of callbacks to be invoked when collection is performed */
69static PyObject *callbacks = NULL;
70
71/* This is the number of objects that survived the last full collection. It
Antoine Pitrou14b78f52009-01-09 22:27:08 +000072 approximates the number of long lived objects tracked by the GC.
73
74 (by "full collection", we mean a collection of the oldest generation).
75*/
76static Py_ssize_t long_lived_total = 0;
77
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +000078/* This is the number of objects that survived all "non-full" collections,
Antoine Pitrou14b78f52009-01-09 22:27:08 +000079 and are awaiting to undergo a full collection for the first time.
80
81*/
82static Py_ssize_t long_lived_pending = 0;
83
84/*
85 NOTE: about the counting of long-lived objects.
86
87 To limit the cost of garbage collection, there are two strategies;
88 - make each collection faster, e.g. by scanning fewer objects
89 - do less collections
90 This heuristic is about the latter strategy.
91
92 In addition to the various configurable thresholds, we only trigger a
93 full collection if the ratio
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 long_lived_pending / long_lived_total
Antoine Pitrou14b78f52009-01-09 22:27:08 +000095 is above a given value (hardwired to 25%).
96
97 The reason is that, while "non-full" collections (i.e., collections of
98 the young and middle generations) will always examine roughly the same
99 number of objects -- determined by the aforementioned thresholds --,
100 the cost of a full collection is proportional to the total number of
101 long-lived objects, which is virtually unbounded.
102
103 Indeed, it has been remarked that doing a full collection every
104 <constant number> of object creations entails a dramatic performance
105 degradation in workloads which consist in creating and storing lots of
106 long-lived objects (e.g. building a large list of GC-tracked objects would
107 show quadratic performance, instead of linear as expected: see issue #4074).
108
109 Using the above ratio, instead, yields amortized linear performance in
110 the total number of objects (the effect of which can be summarized
111 thusly: "each full garbage collection is more and more costly as the
112 number of objects grows, but we do fewer and fewer of them").
113
114 This heuristic was suggested by Martin von Löwis on python-dev in
115 June 2008. His original analysis and proposal can be found at:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 http://mail.python.org/pipermail/python-dev/2008-June/080579.html
Antoine Pitrou14b78f52009-01-09 22:27:08 +0000117*/
118
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200119/*
120 NOTE: about untracking of mutable objects.
Victor Stinnerc1eb26c2013-07-08 22:15:05 +0200121
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200122 Certain types of container cannot participate in a reference cycle, and
123 so do not need to be tracked by the garbage collector. Untracking these
124 objects reduces the cost of garbage collections. However, determining
125 which objects may be untracked is not free, and the costs must be
126 weighed against the benefits for garbage collection.
127
128 There are two possible strategies for when to untrack a container:
129
130 i) When the container is created.
131 ii) When the container is examined by the garbage collector.
132
133 Tuples containing only immutable objects (integers, strings etc, and
134 recursively, tuples of immutable objects) do not need to be tracked.
135 The interpreter creates a large number of tuples, many of which will
136 not survive until garbage collection. It is therefore not worthwhile
137 to untrack eligible tuples at creation time.
138
Victor Stinnerc1eb26c2013-07-08 22:15:05 +0200139 Instead, all tuples except the empty tuple are tracked when created.
140 During garbage collection it is determined whether any surviving tuples
141 can be untracked. A tuple can be untracked if all of its contents are
142 already not tracked. Tuples are examined for untracking in all garbage
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200143 collection cycles. It may take more than one cycle to untrack a tuple.
144
145 Dictionaries containing only immutable objects also do not need to be
146 tracked. Dictionaries are untracked when created. If a tracked item is
147 inserted into a dictionary (either as a key or value), the dictionary
148 becomes tracked. During a full garbage collection (all generations),
149 the collector will untrack any dictionaries whose contents are not
150 tracked.
151
152 The module provides the python function is_tracked(obj), which returns
153 the CURRENT tracking status of the object. Subsequent garbage
154 collections may change the tracking status of the object.
Victor Stinnerc1eb26c2013-07-08 22:15:05 +0200155
156 Untracking of certain containers was introduced in issue #4688, and
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200157 the algorithm was refined in response to issue #14775.
158*/
Antoine Pitrou14b78f52009-01-09 22:27:08 +0000159
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000160/* set for debugging information */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161#define DEBUG_STATS (1<<0) /* print collection statistics */
162#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
163#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
164#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
165#define DEBUG_LEAK DEBUG_COLLECTABLE | \
166 DEBUG_UNCOLLECTABLE | \
167 DEBUG_SAVEALL
Jeremy Hyltonb709df32000-09-01 02:47:25 +0000168static int debug;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000169static PyObject *tmod = NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000170
Antoine Pitroud4156c12012-10-30 22:43:19 +0100171/* Running stats per generation */
172struct gc_generation_stats {
173 /* total number of collections */
174 Py_ssize_t collections;
175 /* total number of collected objects */
176 Py_ssize_t collected;
177 /* total number of uncollectable objects (put into gc.garbage) */
178 Py_ssize_t uncollectable;
179};
180
181static struct gc_generation_stats generation_stats[NUM_GENERATIONS];
182
Tim Peters6fc13d92002-07-02 18:12:35 +0000183/*--------------------------------------------------------------------------
184gc_refs values.
Neil Schemenauer43411b52001-08-30 00:05:51 +0000185
Tim Peters6fc13d92002-07-02 18:12:35 +0000186Between collections, every gc'ed object has one of two gc_refs values:
187
188GC_UNTRACKED
189 The initial state; objects returned by PyObject_GC_Malloc are in this
190 state. The object doesn't live in any generation list, and its
191 tp_traverse slot must not be called.
192
193GC_REACHABLE
194 The object lives in some generation list, and its tp_traverse is safe to
195 call. An object transitions to GC_REACHABLE when PyObject_GC_Track
196 is called.
197
198During a collection, gc_refs can temporarily take on other states:
199
200>= 0
201 At the start of a collection, update_refs() copies the true refcount
202 to gc_refs, for each object in the generation being collected.
203 subtract_refs() then adjusts gc_refs so that it equals the number of
204 times an object is referenced directly from outside the generation
205 being collected.
Martin v. Löwis774348c2002-11-09 19:54:06 +0000206 gc_refs remains >= 0 throughout these steps.
Tim Peters6fc13d92002-07-02 18:12:35 +0000207
208GC_TENTATIVELY_UNREACHABLE
209 move_unreachable() then moves objects not reachable (whether directly or
210 indirectly) from outside the generation into an "unreachable" set.
211 Objects that are found to be reachable have gc_refs set to GC_REACHABLE
212 again. Objects that are found to be unreachable have gc_refs set to
213 GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing
214 this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may
215 transition back to GC_REACHABLE.
216
217 Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates
218 for collection. If it's decided not to collect such an object (e.g.,
219 it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
220----------------------------------------------------------------------------
221*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
223#define GC_REACHABLE _PyGC_REFS_REACHABLE
224#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
Tim Peters19b74c72002-07-01 03:52:19 +0000225
Tim Peters6fc13d92002-07-02 18:12:35 +0000226#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)
Tim Peters19b74c72002-07-01 03:52:19 +0000227#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)
228#define IS_TENTATIVELY_UNREACHABLE(o) ( \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
Neil Schemenauera2b11ec2002-05-21 15:53:24 +0000230
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000231/*** list functions ***/
232
233static void
234gc_list_init(PyGC_Head *list)
235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 list->gc.gc_prev = list;
237 list->gc.gc_next = list;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000238}
239
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000240static int
241gc_list_is_empty(PyGC_Head *list)
242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 return (list->gc.gc_next == list);
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000244}
245
Tim Peterse2d59182004-11-01 01:39:08 +0000246#if 0
247/* This became unused after gc_list_move() was introduced. */
248/* Append `node` to `list`. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000249static void
250gc_list_append(PyGC_Head *node, PyGC_Head *list)
251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 node->gc.gc_next = list;
253 node->gc.gc_prev = list->gc.gc_prev;
254 node->gc.gc_prev->gc.gc_next = node;
255 list->gc.gc_prev = node;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000256}
Tim Peterse2d59182004-11-01 01:39:08 +0000257#endif
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000258
Tim Peterse2d59182004-11-01 01:39:08 +0000259/* Remove `node` from the gc list it's currently in. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000260static void
261gc_list_remove(PyGC_Head *node)
262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
264 node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
265 node->gc.gc_next = NULL; /* object is not currently tracked */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000266}
267
Tim Peterse2d59182004-11-01 01:39:08 +0000268/* Move `node` from the gc list it's currently in (which is not explicitly
269 * named here) to the end of `list`. This is semantically the same as
270 * gc_list_remove(node) followed by gc_list_append(node, list).
271 */
272static void
273gc_list_move(PyGC_Head *node, PyGC_Head *list)
274{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 PyGC_Head *new_prev;
276 PyGC_Head *current_prev = node->gc.gc_prev;
277 PyGC_Head *current_next = node->gc.gc_next;
278 /* Unlink from current list. */
279 current_prev->gc.gc_next = current_next;
280 current_next->gc.gc_prev = current_prev;
281 /* Relink at end of new list. */
282 new_prev = node->gc.gc_prev = list->gc.gc_prev;
283 new_prev->gc.gc_next = list->gc.gc_prev = node;
284 node->gc.gc_next = list;
Tim Peterse2d59182004-11-01 01:39:08 +0000285}
286
287/* append list `from` onto list `to`; `from` becomes an empty list */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000288static void
289gc_list_merge(PyGC_Head *from, PyGC_Head *to)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 PyGC_Head *tail;
292 assert(from != to);
293 if (!gc_list_is_empty(from)) {
294 tail = to->gc.gc_prev;
295 tail->gc.gc_next = from->gc.gc_next;
296 tail->gc.gc_next->gc.gc_prev = tail;
297 to->gc.gc_prev = from->gc.gc_prev;
298 to->gc.gc_prev->gc.gc_next = to;
299 }
300 gc_list_init(from);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000301}
302
Neal Norwitz7b216c52006-03-04 20:01:53 +0000303static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000304gc_list_size(PyGC_Head *list)
305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 PyGC_Head *gc;
307 Py_ssize_t n = 0;
308 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
309 n++;
310 }
311 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000312}
313
Tim Peters259272b2003-04-06 19:41:39 +0000314/* Append objects in a GC list to a Python list.
315 * Return 0 if all OK, < 0 if error (out of memory for list).
316 */
317static int
318append_objects(PyObject *py_list, PyGC_Head *gc_list)
319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 PyGC_Head *gc;
321 for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
322 PyObject *op = FROM_GC(gc);
323 if (op != py_list) {
324 if (PyList_Append(py_list, op)) {
325 return -1; /* exception */
326 }
327 }
328 }
329 return 0;
Tim Peters259272b2003-04-06 19:41:39 +0000330}
331
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000332/*** end of list stuff ***/
333
334
Tim Peters19b74c72002-07-01 03:52:19 +0000335/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects
336 * in containers, and is GC_REACHABLE for all tracked gc objects not in
337 * containers.
Tim Peters88396172002-06-30 17:56:40 +0000338 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000339static void
340update_refs(PyGC_Head *containers)
341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 PyGC_Head *gc = containers->gc.gc_next;
343 for (; gc != containers; gc = gc->gc.gc_next) {
344 assert(gc->gc.gc_refs == GC_REACHABLE);
345 gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
346 /* Python's cyclic gc should never see an incoming refcount
347 * of 0: if something decref'ed to 0, it should have been
348 * deallocated immediately at that time.
349 * Possible cause (if the assert triggers): a tp_dealloc
350 * routine left a gc-aware object tracked during its teardown
351 * phase, and did something-- or allowed something to happen --
352 * that called back into Python. gc can trigger then, and may
353 * see the still-tracked dying object. Before this assert
354 * was added, such mistakes went on to allow gc to try to
355 * delete the object again. In a debug build, that caused
356 * a mysterious segfault, when _Py_ForgetReference tried
357 * to remove the object from the doubly-linked list of all
358 * objects a second time. In a release build, an actual
359 * double deallocation occurred, which leads to corruption
360 * of the allocator's internal bookkeeping pointers. That's
361 * so serious that maybe this should be a release-build
362 * check instead of an assert?
363 */
364 assert(gc->gc.gc_refs != 0);
365 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000366}
367
Tim Peters19b74c72002-07-01 03:52:19 +0000368/* A traversal callback for subtract_refs. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000369static int
370visit_decref(PyObject *op, void *data)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 assert(op != NULL);
373 if (PyObject_IS_GC(op)) {
374 PyGC_Head *gc = AS_GC(op);
375 /* We're only interested in gc_refs for objects in the
376 * generation being collected, which can be recognized
377 * because only they have positive gc_refs.
378 */
379 assert(gc->gc.gc_refs != 0); /* else refcount was too small */
380 if (gc->gc.gc_refs > 0)
381 gc->gc.gc_refs--;
382 }
383 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000384}
385
Tim Peters19b74c72002-07-01 03:52:19 +0000386/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
387 * for all objects in containers, and is GC_REACHABLE for all tracked gc
388 * objects not in containers. The ones with gc_refs > 0 are directly
389 * reachable from outside containers, and so can't be collected.
390 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000391static void
392subtract_refs(PyGC_Head *containers)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 traverseproc traverse;
395 PyGC_Head *gc = containers->gc.gc_next;
396 for (; gc != containers; gc=gc->gc.gc_next) {
397 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
398 (void) traverse(FROM_GC(gc),
399 (visitproc)visit_decref,
400 NULL);
401 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000402}
403
Tim Peters19b74c72002-07-01 03:52:19 +0000404/* A traversal callback for move_unreachable. */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000405static int
Tim Peters19b74c72002-07-01 03:52:19 +0000406visit_reachable(PyObject *op, PyGC_Head *reachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (PyObject_IS_GC(op)) {
409 PyGC_Head *gc = AS_GC(op);
410 const Py_ssize_t gc_refs = gc->gc.gc_refs;
Tim Peters19b74c72002-07-01 03:52:19 +0000411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (gc_refs == 0) {
413 /* This is in move_unreachable's 'young' list, but
414 * the traversal hasn't yet gotten to it. All
415 * we need to do is tell move_unreachable that it's
416 * reachable.
417 */
418 gc->gc.gc_refs = 1;
419 }
420 else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
421 /* This had gc_refs = 0 when move_unreachable got
422 * to it, but turns out it's reachable after all.
423 * Move it back to move_unreachable's 'young' list,
424 * and move_unreachable will eventually get to it
425 * again.
426 */
427 gc_list_move(gc, reachable);
428 gc->gc.gc_refs = 1;
429 }
430 /* Else there's nothing to do.
431 * If gc_refs > 0, it must be in move_unreachable's 'young'
432 * list, and move_unreachable will eventually get to it.
433 * If gc_refs == GC_REACHABLE, it's either in some other
434 * generation so we don't care about it, or move_unreachable
435 * already dealt with it.
436 * If gc_refs == GC_UNTRACKED, it must be ignored.
437 */
438 else {
439 assert(gc_refs > 0
440 || gc_refs == GC_REACHABLE
441 || gc_refs == GC_UNTRACKED);
442 }
443 }
444 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000445}
446
Tim Peters19b74c72002-07-01 03:52:19 +0000447/* Move the unreachable objects from young to unreachable. After this,
448 * all objects in young have gc_refs = GC_REACHABLE, and all objects in
449 * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked
450 * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.
451 * All objects in young after this are directly or indirectly reachable
452 * from outside the original young; and all objects in unreachable are
453 * not.
Tim Peters88396172002-06-30 17:56:40 +0000454 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000455static void
Tim Peters19b74c72002-07-01 03:52:19 +0000456move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyGC_Head *gc = young->gc.gc_next;
Tim Peters19b74c72002-07-01 03:52:19 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 /* Invariants: all objects "to the left" of us in young have gc_refs
461 * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
462 * from outside the young list as it was at entry. All other objects
463 * from the original young "to the left" of us are in unreachable now,
464 * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
465 * left of us in 'young' now have been scanned, and no objects here
466 * or to the right have been scanned yet.
467 */
Tim Peters19b74c72002-07-01 03:52:19 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 while (gc != young) {
470 PyGC_Head *next;
Tim Peters19b74c72002-07-01 03:52:19 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (gc->gc.gc_refs) {
473 /* gc is definitely reachable from outside the
474 * original 'young'. Mark it as such, and traverse
475 * its pointers to find any other objects that may
476 * be directly reachable from it. Note that the
477 * call to tp_traverse may append objects to young,
478 * so we have to wait until it returns to determine
479 * the next object to visit.
480 */
481 PyObject *op = FROM_GC(gc);
482 traverseproc traverse = Py_TYPE(op)->tp_traverse;
483 assert(gc->gc.gc_refs > 0);
484 gc->gc.gc_refs = GC_REACHABLE;
485 (void) traverse(op,
486 (visitproc)visit_reachable,
487 (void *)young);
488 next = gc->gc.gc_next;
489 if (PyTuple_CheckExact(op)) {
490 _PyTuple_MaybeUntrack(op);
491 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 }
493 else {
494 /* This *may* be unreachable. To make progress,
495 * assume it is. gc isn't directly reachable from
496 * any object we've already traversed, but may be
497 * reachable from an object we haven't gotten to yet.
498 * visit_reachable will eventually move gc back into
499 * young if that's so, and we'll see it again.
500 */
501 next = gc->gc.gc_next;
502 gc_list_move(gc, unreachable);
503 gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
504 }
505 gc = next;
506 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000507}
508
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200509/* Try to untrack all currently tracked dictionaries */
510static void
511untrack_dicts(PyGC_Head *head)
512{
513 PyGC_Head *next, *gc = head->gc.gc_next;
514 while (gc != head) {
515 PyObject *op = FROM_GC(gc);
516 next = gc->gc.gc_next;
517 if (PyDict_CheckExact(op))
518 _PyDict_MaybeUntrack(op);
519 gc = next;
520 }
521}
522
Amaury Forgeot d'Arcad8dcd52007-12-10 23:58:35 +0000523/* Return true if object has a finalization method. */
Neil Schemenauera765c122001-11-01 17:35:23 +0000524static int
525has_finalizer(PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000526{
Antoine Pitrou93963562013-05-14 20:37:52 +0200527 if (PyGen_CheckExact(op))
528 return PyGen_NeedsFinalizing((PyGenObject *)op);
529 else
530 return op->ob_type->tp_del != NULL;
Neil Schemenauera765c122001-11-01 17:35:23 +0000531}
532
Tim Petersead8b7a2004-10-30 23:09:22 +0000533/* Move the objects in unreachable with __del__ methods into `finalizers`.
534 * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the
535 * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000536 */
Neil Schemenauera765c122001-11-01 17:35:23 +0000537static void
Tim Petersead8b7a2004-10-30 23:09:22 +0000538move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
Neil Schemenauera765c122001-11-01 17:35:23 +0000539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyGC_Head *gc;
541 PyGC_Head *next;
Tim Petersf6b80452003-04-07 19:21:15 +0000542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 /* March over unreachable. Move objects with finalizers into
544 * `finalizers`.
545 */
546 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
547 PyObject *op = FROM_GC(gc);
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 assert(IS_TENTATIVELY_UNREACHABLE(op));
550 next = gc->gc.gc_next;
Tim Petersf6ae7a42003-04-05 18:40:50 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (has_finalizer(op)) {
553 gc_list_move(gc, finalizers);
554 gc->gc.gc_refs = GC_REACHABLE;
555 }
556 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000557}
558
Tim Peters19b74c72002-07-01 03:52:19 +0000559/* A traversal callback for move_finalizer_reachable. */
560static int
561visit_move(PyObject *op, PyGC_Head *tolist)
562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (PyObject_IS_GC(op)) {
564 if (IS_TENTATIVELY_UNREACHABLE(op)) {
565 PyGC_Head *gc = AS_GC(op);
566 gc_list_move(gc, tolist);
567 gc->gc.gc_refs = GC_REACHABLE;
568 }
569 }
570 return 0;
Tim Peters19b74c72002-07-01 03:52:19 +0000571}
572
573/* Move objects that are reachable from finalizers, from the unreachable set
Tim Petersf6b80452003-04-07 19:21:15 +0000574 * into finalizers set.
Tim Peters19b74c72002-07-01 03:52:19 +0000575 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000576static void
Tim Petersf6b80452003-04-07 19:21:15 +0000577move_finalizer_reachable(PyGC_Head *finalizers)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 traverseproc traverse;
580 PyGC_Head *gc = finalizers->gc.gc_next;
581 for (; gc != finalizers; gc = gc->gc.gc_next) {
582 /* Note that the finalizers list may grow during this. */
583 traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
584 (void) traverse(FROM_GC(gc),
585 (visitproc)visit_move,
586 (void *)finalizers);
587 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000588}
589
Tim Petersead8b7a2004-10-30 23:09:22 +0000590/* Clear all weakrefs to unreachable objects, and if such a weakref has a
591 * callback, invoke it if necessary. Note that it's possible for such
592 * weakrefs to be outside the unreachable set -- indeed, those are precisely
593 * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
594 * overview & some details. Some weakrefs with callbacks may be reclaimed
595 * directly by this routine; the number reclaimed is the return value. Other
596 * weakrefs with callbacks may be moved into the `old` generation. Objects
597 * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
598 * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
599 * no object in `unreachable` is weakly referenced anymore.
Tim Peters403a2032003-11-20 21:21:46 +0000600 */
601static int
Tim Petersead8b7a2004-10-30 23:09:22 +0000602handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
Tim Peters403a2032003-11-20 21:21:46 +0000603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 PyGC_Head *gc;
605 PyObject *op; /* generally FROM_GC(gc) */
606 PyWeakReference *wr; /* generally a cast of op */
607 PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
608 PyGC_Head *next;
609 int num_freed = 0;
Tim Peters403a2032003-11-20 21:21:46 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 gc_list_init(&wrcb_to_call);
Tim Peters403a2032003-11-20 21:21:46 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 /* Clear all weakrefs to the objects in unreachable. If such a weakref
614 * also has a callback, move it into `wrcb_to_call` if the callback
615 * needs to be invoked. Note that we cannot invoke any callbacks until
616 * all weakrefs to unreachable objects are cleared, lest the callback
617 * resurrect an unreachable object via a still-active weakref. We
618 * make another pass over wrcb_to_call, invoking callbacks, after this
619 * pass completes.
620 */
621 for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
622 PyWeakReference **wrlist;
Tim Petersead8b7a2004-10-30 23:09:22 +0000623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 op = FROM_GC(gc);
625 assert(IS_TENTATIVELY_UNREACHABLE(op));
626 next = gc->gc.gc_next;
Tim Petersead8b7a2004-10-30 23:09:22 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
629 continue;
Tim Petersead8b7a2004-10-30 23:09:22 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* It supports weakrefs. Does it have any? */
632 wrlist = (PyWeakReference **)
633 PyObject_GET_WEAKREFS_LISTPTR(op);
Tim Petersead8b7a2004-10-30 23:09:22 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* `op` may have some weakrefs. March over the list, clear
636 * all the weakrefs, and move the weakrefs with callbacks
637 * that must be called into wrcb_to_call.
638 */
639 for (wr = *wrlist; wr != NULL; wr = *wrlist) {
640 PyGC_Head *wrasgc; /* AS_GC(wr) */
Tim Petersead8b7a2004-10-30 23:09:22 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 /* _PyWeakref_ClearRef clears the weakref but leaves
643 * the callback pointer intact. Obscure: it also
644 * changes *wrlist.
645 */
646 assert(wr->wr_object == op);
647 _PyWeakref_ClearRef(wr);
648 assert(wr->wr_object == Py_None);
649 if (wr->wr_callback == NULL)
650 continue; /* no callback */
Tim Petersead8b7a2004-10-30 23:09:22 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 /* Headache time. `op` is going away, and is weakly referenced by
653 * `wr`, which has a callback. Should the callback be invoked? If wr
654 * is also trash, no:
655 *
656 * 1. There's no need to call it. The object and the weakref are
657 * both going away, so it's legitimate to pretend the weakref is
658 * going away first. The user has to ensure a weakref outlives its
659 * referent if they want a guarantee that the wr callback will get
660 * invoked.
661 *
662 * 2. It may be catastrophic to call it. If the callback is also in
663 * cyclic trash (CT), then although the CT is unreachable from
664 * outside the current generation, CT may be reachable from the
665 * callback. Then the callback could resurrect insane objects.
666 *
667 * Since the callback is never needed and may be unsafe in this case,
668 * wr is simply left in the unreachable set. Note that because we
669 * already called _PyWeakref_ClearRef(wr), its callback will never
670 * trigger.
671 *
672 * OTOH, if wr isn't part of CT, we should invoke the callback: the
673 * weakref outlived the trash. Note that since wr isn't CT in this
674 * case, its callback can't be CT either -- wr acted as an external
675 * root to this generation, and therefore its callback did too. So
676 * nothing in CT is reachable from the callback either, so it's hard
677 * to imagine how calling it later could create a problem for us. wr
678 * is moved to wrcb_to_call in this case.
679 */
680 if (IS_TENTATIVELY_UNREACHABLE(wr))
681 continue;
682 assert(IS_REACHABLE(wr));
Tim Peterscc2a8662004-10-31 22:12:43 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* Create a new reference so that wr can't go away
685 * before we can process it again.
686 */
687 Py_INCREF(wr);
Tim Petersead8b7a2004-10-30 23:09:22 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 /* Move wr to wrcb_to_call, for the next pass. */
690 wrasgc = AS_GC(wr);
691 assert(wrasgc != next); /* wrasgc is reachable, but
692 next isn't, so they can't
693 be the same */
694 gc_list_move(wrasgc, &wrcb_to_call);
695 }
696 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 /* Invoke the callbacks we decided to honor. It's safe to invoke them
699 * because they can't reference unreachable objects.
700 */
701 while (! gc_list_is_empty(&wrcb_to_call)) {
702 PyObject *temp;
703 PyObject *callback;
Tim Petersead8b7a2004-10-30 23:09:22 +0000704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 gc = wrcb_to_call.gc.gc_next;
706 op = FROM_GC(gc);
707 assert(IS_REACHABLE(op));
708 assert(PyWeakref_Check(op));
709 wr = (PyWeakReference *)op;
710 callback = wr->wr_callback;
711 assert(callback != NULL);
Tim Petersead8b7a2004-10-30 23:09:22 +0000712
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 /* copy-paste of weakrefobject.c's handle_callback() */
714 temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
715 if (temp == NULL)
716 PyErr_WriteUnraisable(callback);
717 else
718 Py_DECREF(temp);
Tim Petersead8b7a2004-10-30 23:09:22 +0000719
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 /* Give up the reference we created in the first pass. When
721 * op's refcount hits 0 (which it may or may not do right now),
722 * op's tp_dealloc will decref op->wr_callback too. Note
723 * that the refcount probably will hit 0 now, and because this
724 * weakref was reachable to begin with, gc didn't already
725 * add it to its count of freed objects. Example: a reachable
726 * weak value dict maps some key to this reachable weakref.
727 * The callback removes this key->weakref mapping from the
728 * dict, leaving no other references to the weakref (excepting
729 * ours).
730 */
731 Py_DECREF(op);
732 if (wrcb_to_call.gc.gc_next == gc) {
733 /* object is still alive -- move it */
734 gc_list_move(gc, old);
735 }
736 else
737 ++num_freed;
738 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return num_freed;
Tim Peters403a2032003-11-20 21:21:46 +0000741}
742
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000743static void
Jeremy Hylton06257772000-08-31 15:10:24 +0000744debug_cycle(char *msg, PyObject *op)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000745{
Victor Stinner499dfcf2011-03-21 13:26:24 +0100746 PySys_FormatStderr("gc: %s <%s %p>\n",
747 msg, Py_TYPE(op)->tp_name, op);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000748}
749
Tim Petersbf384c22003-04-06 00:11:39 +0000750/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
751 * only from such cycles).
Tim Petersf6b80452003-04-07 19:21:15 +0000752 * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
753 * garbage list (a Python list), else only the objects in finalizers with
754 * __del__ methods are appended to garbage. All objects in finalizers are
755 * merged into the old list regardless.
Tim Peters259272b2003-04-06 19:41:39 +0000756 * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).
757 * The finalizers list is made empty on a successful return.
Tim Petersbf384c22003-04-06 00:11:39 +0000758 */
Tim Peters259272b2003-04-06 19:41:39 +0000759static int
Tim Petersf6b80452003-04-07 19:21:15 +0000760handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyGC_Head *gc = finalizers->gc.gc_next;
Tim Petersf6b80452003-04-07 19:21:15 +0000763
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 if (garbage == NULL) {
765 garbage = PyList_New(0);
766 if (garbage == NULL)
767 Py_FatalError("gc couldn't create gc.garbage list");
768 }
769 for (; gc != finalizers; gc = gc->gc.gc_next) {
770 PyObject *op = FROM_GC(gc);
Tim Petersf6b80452003-04-07 19:21:15 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
773 if (PyList_Append(garbage, op) < 0)
774 return -1;
775 }
776 }
Tim Petersf6b80452003-04-07 19:21:15 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 gc_list_merge(finalizers, old);
779 return 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000780}
781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782/* Break reference cycles by clearing the containers involved. This is
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000783 * tricky business as the lists can be changing and we don't know which
Tim Peters19b74c72002-07-01 03:52:19 +0000784 * objects may be freed. It is possible I screwed something up here.
785 */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000786static void
Jeremy Hyltonce136e92003-04-04 19:59:06 +0000787delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 inquiry clear;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 while (!gc_list_is_empty(collectable)) {
792 PyGC_Head *gc = collectable->gc.gc_next;
793 PyObject *op = FROM_GC(gc);
Tim Peters88396172002-06-30 17:56:40 +0000794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(IS_TENTATIVELY_UNREACHABLE(op));
796 if (debug & DEBUG_SAVEALL) {
797 PyList_Append(garbage, op);
798 }
799 else {
800 if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
801 Py_INCREF(op);
802 clear(op);
803 Py_DECREF(op);
804 }
805 }
806 if (collectable->gc.gc_next == gc) {
807 /* object is still alive, move it, it may die later */
808 gc_list_move(gc, old);
809 gc->gc.gc_refs = GC_REACHABLE;
810 }
811 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000812}
813
Christian Heimesa156e092008-02-16 07:38:31 +0000814/* Clear all free lists
815 * All free lists are cleared during the collection of the highest generation.
816 * Allocated items in the free list may keep a pymalloc arena occupied.
817 * Clearing the free lists may give back memory to the OS earlier.
818 */
819static void
820clear_freelists(void)
821{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 (void)PyMethod_ClearFreeList();
823 (void)PyFrame_ClearFreeList();
824 (void)PyCFunction_ClearFreeList();
825 (void)PyTuple_ClearFreeList();
826 (void)PyUnicode_ClearFreeList();
827 (void)PyFloat_ClearFreeList();
Antoine Pitrou9a812cb2011-11-15 00:00:12 +0100828 (void)PyList_ClearFreeList();
829 (void)PyDict_ClearFreeList();
Antoine Pitrou093ce9c2011-12-16 11:24:27 +0100830 (void)PySet_ClearFreeList();
Christian Heimesa156e092008-02-16 07:38:31 +0000831}
832
Antoine Pitrou621601a2008-12-17 23:18:19 +0000833static double
834get_time(void)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 double result = 0;
837 if (tmod != NULL) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200838 _Py_IDENTIFIER(time);
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200839
840 PyObject *f = _PyObject_CallMethodId(tmod, &PyId_time, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (f == NULL) {
842 PyErr_Clear();
843 }
844 else {
845 if (PyFloat_Check(f))
846 result = PyFloat_AsDouble(f);
847 Py_DECREF(f);
848 }
849 }
850 return result;
Antoine Pitrou621601a2008-12-17 23:18:19 +0000851}
852
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000853/* This is the main function. Read this to understand how the
854 * collection process works. */
Neal Norwitz7b216c52006-03-04 20:01:53 +0000855static Py_ssize_t
Antoine Pitroufef34e32013-05-19 01:11:58 +0200856collect(int generation, Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
857 int nofail)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 int i;
860 Py_ssize_t m = 0; /* # objects collected */
861 Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
862 PyGC_Head *young; /* the generation we are examining */
863 PyGC_Head *old; /* next older generation */
864 PyGC_Head unreachable; /* non-problematic unreachable trash */
865 PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
866 PyGC_Head *gc;
867 double t1 = 0.0;
Antoine Pitroud4156c12012-10-30 22:43:19 +0100868 struct gc_generation_stats *stats = &generation_stats[generation];
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (debug & DEBUG_STATS) {
871 PySys_WriteStderr("gc: collecting generation %d...\n",
872 generation);
873 PySys_WriteStderr("gc: objects in each generation:");
874 for (i = 0; i < NUM_GENERATIONS; i++)
875 PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
876 gc_list_size(GEN_HEAD(i)));
877 t1 = get_time();
878 PySys_WriteStderr("\n");
879 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* update collection and allocation counters */
882 if (generation+1 < NUM_GENERATIONS)
883 generations[generation+1].count += 1;
884 for (i = 0; i <= generation; i++)
885 generations[i].count = 0;
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* merge younger generations with one we are currently collecting */
888 for (i = 0; i < generation; i++) {
889 gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
890 }
Neil Schemenauer2880ae52002-05-04 05:35:20 +0000891
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 /* handy references */
893 young = GEN_HEAD(generation);
894 if (generation < NUM_GENERATIONS-1)
895 old = GEN_HEAD(generation+1);
896 else
897 old = young;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* Using ob_refcnt and gc_refs, calculate which objects in the
900 * container set are reachable from outside the set (i.e., have a
901 * refcount greater than 0 when all the references within the
902 * set are taken into account).
903 */
904 update_refs(young);
905 subtract_refs(young);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 /* Leave everything reachable from outside young in young, and move
908 * everything else (in young) to unreachable.
909 * NOTE: This used to move the reachable objects into a reachable
910 * set instead. But most things usually turn out to be reachable,
911 * so it's more efficient to move the unreachable things.
912 */
913 gc_list_init(&unreachable);
914 move_unreachable(young, &unreachable);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 /* Move reachable objects to next generation. */
917 if (young != old) {
918 if (generation == NUM_GENERATIONS - 2) {
919 long_lived_pending += gc_list_size(young);
920 }
921 gc_list_merge(young, old);
922 }
923 else {
Antoine Pitroue1ad3da2012-05-28 22:22:34 +0200924 /* We only untrack dicts in full collections, to avoid quadratic
925 dict build-up. See issue #14775. */
926 untrack_dicts(young);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 long_lived_pending = 0;
928 long_lived_total = gc_list_size(young);
929 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* All objects in unreachable are trash, but objects reachable from
932 * finalizers can't safely be deleted. Python programmers should take
933 * care not to create such things. For Python, finalizers means
934 * instance objects with __del__ methods. Weakrefs with callbacks
935 * can also call arbitrary Python code but they will be dealt with by
936 * handle_weakrefs().
937 */
938 gc_list_init(&finalizers);
939 move_finalizers(&unreachable, &finalizers);
940 /* finalizers contains the unreachable objects with a finalizer;
941 * unreachable objects reachable *from* those are also uncollectable,
942 * and we move those into the finalizers list too.
943 */
944 move_finalizer_reachable(&finalizers);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 /* Collect statistics on collectable objects found and print
947 * debugging information.
948 */
949 for (gc = unreachable.gc.gc_next; gc != &unreachable;
950 gc = gc->gc.gc_next) {
951 m++;
952 if (debug & DEBUG_COLLECTABLE) {
953 debug_cycle("collectable", FROM_GC(gc));
954 }
955 }
Tim Petersead8b7a2004-10-30 23:09:22 +0000956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* Clear weakrefs and invoke callbacks as necessary. */
958 m += handle_weakrefs(&unreachable, old);
Tim Petersead8b7a2004-10-30 23:09:22 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* Call tp_clear on objects in the unreachable set. This will cause
961 * the reference cycles to be broken. It may also cause some objects
962 * in finalizers to be freed.
963 */
964 delete_garbage(&unreachable, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000965
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 /* Collect statistics on uncollectable objects found and print
967 * debugging information. */
968 for (gc = finalizers.gc.gc_next;
969 gc != &finalizers;
970 gc = gc->gc.gc_next) {
971 n++;
972 if (debug & DEBUG_UNCOLLECTABLE)
973 debug_cycle("uncollectable", FROM_GC(gc));
974 }
975 if (debug & DEBUG_STATS) {
976 double t2 = get_time();
977 if (m == 0 && n == 0)
978 PySys_WriteStderr("gc: done");
979 else
980 PySys_WriteStderr(
981 "gc: done, "
982 "%" PY_FORMAT_SIZE_T "d unreachable, "
983 "%" PY_FORMAT_SIZE_T "d uncollectable",
984 n+m, n);
985 if (t1 && t2) {
986 PySys_WriteStderr(", %.4fs elapsed", t2-t1);
987 }
988 PySys_WriteStderr(".\n");
989 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 /* Append instances in the uncollectable set to a Python
992 * reachable list of garbage. The programmer has to deal with
993 * this if they insist on creating this type of structure.
994 */
995 (void)handle_finalizers(&finalizers, old);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +0000996
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 /* Clear free list only during the collection of the highest
998 * generation */
999 if (generation == NUM_GENERATIONS-1) {
1000 clear_freelists();
1001 }
Christian Heimesa156e092008-02-16 07:38:31 +00001002
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (PyErr_Occurred()) {
Antoine Pitroufef34e32013-05-19 01:11:58 +02001004 if (nofail) {
1005 PyErr_Clear();
1006 }
1007 else {
1008 if (gc_str == NULL)
1009 gc_str = PyUnicode_FromString("garbage collection");
1010 PyErr_WriteUnraisable(gc_str);
1011 Py_FatalError("unexpected exception during garbage collection");
1012 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 }
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001014
Antoine Pitroud4156c12012-10-30 22:43:19 +01001015 /* Update stats */
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001016 if (n_collected)
1017 *n_collected = m;
1018 if (n_uncollectable)
1019 *n_uncollectable = n;
Antoine Pitroud4156c12012-10-30 22:43:19 +01001020 stats->collections++;
1021 stats->collected += m;
1022 stats->uncollectable += n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return n+m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001024}
1025
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001026/* Invoke progress callbacks to notify clients that garbage collection
1027 * is starting or stopping
1028 */
1029static void
1030invoke_gc_callback(const char *phase, int generation,
1031 Py_ssize_t collected, Py_ssize_t uncollectable)
1032{
1033 Py_ssize_t i;
1034 PyObject *info = NULL;
1035
1036 /* we may get called very early */
1037 if (callbacks == NULL)
1038 return;
1039 /* The local variable cannot be rebound, check it for sanity */
1040 assert(callbacks != NULL && PyList_CheckExact(callbacks));
1041 if (PyList_GET_SIZE(callbacks) != 0) {
1042 info = Py_BuildValue("{sisnsn}",
1043 "generation", generation,
1044 "collected", collected,
1045 "uncollectable", uncollectable);
1046 if (info == NULL) {
1047 PyErr_WriteUnraisable(NULL);
1048 return;
1049 }
1050 }
1051 for (i=0; i<PyList_GET_SIZE(callbacks); i++) {
1052 PyObject *r, *cb = PyList_GET_ITEM(callbacks, i);
1053 Py_INCREF(cb); /* make sure cb doesn't go away */
1054 r = PyObject_CallFunction(cb, "sO", phase, info);
1055 Py_XDECREF(r);
1056 if (r == NULL)
1057 PyErr_WriteUnraisable(cb);
1058 Py_DECREF(cb);
1059 }
1060 Py_XDECREF(info);
1061}
1062
1063/* Perform garbage collection of a generation and invoke
1064 * progress callbacks.
1065 */
1066static Py_ssize_t
1067collect_with_callback(int generation)
1068{
1069 Py_ssize_t result, collected, uncollectable;
1070 invoke_gc_callback("start", generation, 0, 0);
Antoine Pitroufef34e32013-05-19 01:11:58 +02001071 result = collect(generation, &collected, &uncollectable, 0);
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001072 invoke_gc_callback("stop", generation, collected, uncollectable);
1073 return result;
1074}
1075
Neal Norwitz7b216c52006-03-04 20:01:53 +00001076static Py_ssize_t
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001077collect_generations(void)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 int i;
1080 Py_ssize_t n = 0;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 /* Find the oldest generation (highest numbered) where the count
1083 * exceeds the threshold. Objects in the that generation and
1084 * generations younger than it will be collected. */
1085 for (i = NUM_GENERATIONS-1; i >= 0; i--) {
1086 if (generations[i].count > generations[i].threshold) {
1087 /* Avoid quadratic performance degradation in number
1088 of tracked objects. See comments at the beginning
1089 of this file, and issue #4074.
1090 */
1091 if (i == NUM_GENERATIONS - 1
1092 && long_lived_pending < long_lived_total / 4)
1093 continue;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001094 n = collect_with_callback(i);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 break;
1096 }
1097 }
1098 return n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001099}
1100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001101PyDoc_STRVAR(gc_enable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001102"enable() -> None\n"
1103"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001104"Enable automatic garbage collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001105
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001106static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001107gc_enable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 enabled = 1;
1110 Py_INCREF(Py_None);
1111 return Py_None;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001112}
1113
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001114PyDoc_STRVAR(gc_disable__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001115"disable() -> None\n"
1116"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001117"Disable automatic garbage collection.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001118
1119static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001120gc_disable(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 enabled = 0;
1123 Py_INCREF(Py_None);
1124 return Py_None;
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001125}
1126
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001127PyDoc_STRVAR(gc_isenabled__doc__,
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001128"isenabled() -> status\n"
1129"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001130"Returns true if automatic garbage collection is enabled.\n");
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001131
1132static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001133gc_isenabled(PyObject *self, PyObject *noargs)
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return PyBool_FromLong((long)enabled);
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001136}
1137
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001138PyDoc_STRVAR(gc_collect__doc__,
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001139"collect([generation]) -> n\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001140"\n"
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001141"With no arguments, run a full collection. The optional argument\n"
1142"may be an integer specifying which generation to collect. A ValueError\n"
1143"is raised if the generation number is invalid.\n\n"
1144"The number of unreachable objects is returned.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001145
1146static PyObject *
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001147gc_collect(PyObject *self, PyObject *args, PyObject *kws)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 static char *keywords[] = {"generation", NULL};
1150 int genarg = NUM_GENERATIONS - 1;
1151 Py_ssize_t n;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
1154 return NULL;
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
1157 PyErr_SetString(PyExc_ValueError, "invalid generation");
1158 return NULL;
1159 }
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001160
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 if (collecting)
1162 n = 0; /* already collecting, don't do anything */
1163 else {
1164 collecting = 1;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001165 n = collect_with_callback(genarg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 collecting = 0;
1167 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return PyLong_FromSsize_t(n);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001170}
1171
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001172PyDoc_STRVAR(gc_set_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001173"set_debug(flags) -> None\n"
1174"\n"
1175"Set the garbage collection debugging flags. Debugging information is\n"
1176"written to sys.stderr.\n"
1177"\n"
1178"flags is an integer and can have the following bits turned on:\n"
1179"\n"
1180" DEBUG_STATS - Print statistics during collection.\n"
1181" DEBUG_COLLECTABLE - Print collectable objects found.\n"
1182" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"
Neil Schemenauer544de1e2000-09-22 15:22:38 +00001183" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001184" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001185
1186static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001187gc_set_debug(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
1190 return NULL;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 Py_INCREF(Py_None);
1193 return Py_None;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001194}
1195
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001196PyDoc_STRVAR(gc_get_debug__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001197"get_debug() -> flags\n"
1198"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001199"Get the garbage collection debugging flags.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001200
1201static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001202gc_get_debug(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return Py_BuildValue("i", debug);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001205}
1206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001207PyDoc_STRVAR(gc_set_thresh__doc__,
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001208"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001209"\n"
1210"Sets the collection thresholds. Setting threshold0 to zero disables\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001211"collection.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001212
1213static PyObject *
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001214gc_set_thresh(PyObject *self, PyObject *args)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 int i;
1217 if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
1218 &generations[0].threshold,
1219 &generations[1].threshold,
1220 &generations[2].threshold))
1221 return NULL;
1222 for (i = 2; i < NUM_GENERATIONS; i++) {
1223 /* generations higher than 2 get the same threshold */
1224 generations[i].threshold = generations[2].threshold;
1225 }
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 Py_INCREF(Py_None);
1228 return Py_None;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001229}
1230
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001231PyDoc_STRVAR(gc_get_thresh__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001232"get_threshold() -> (threshold0, threshold1, threshold2)\n"
1233"\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001234"Return the current collection thresholds\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001235
1236static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001237gc_get_thresh(PyObject *self, PyObject *noargs)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return Py_BuildValue("(iii)",
1240 generations[0].threshold,
1241 generations[1].threshold,
1242 generations[2].threshold);
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001243}
1244
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001245PyDoc_STRVAR(gc_get_count__doc__,
1246"get_count() -> (count0, count1, count2)\n"
1247"\n"
1248"Return the current collection counts\n");
1249
1250static PyObject *
1251gc_get_count(PyObject *self, PyObject *noargs)
1252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return Py_BuildValue("(iii)",
1254 generations[0].count,
1255 generations[1].count,
1256 generations[2].count);
Barry Warsawd3c38ff2006-03-07 09:46:03 +00001257}
1258
Neil Schemenauer48c70342001-08-09 15:38:31 +00001259static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001260referrersvisit(PyObject* obj, PyObject *objs)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001262 Py_ssize_t i;
1263 for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
1264 if (PyTuple_GET_ITEM(objs, i) == obj)
1265 return 1;
1266 return 0;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001267}
1268
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001269static int
Martin v. Löwis560da622001-11-24 09:24:51 +00001270gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyGC_Head *gc;
1273 PyObject *obj;
1274 traverseproc traverse;
1275 for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
1276 obj = FROM_GC(gc);
1277 traverse = Py_TYPE(obj)->tp_traverse;
1278 if (obj == objs || obj == resultlist)
1279 continue;
1280 if (traverse(obj, (visitproc)referrersvisit, objs)) {
1281 if (PyList_Append(resultlist, obj) < 0)
1282 return 0; /* error */
1283 }
1284 }
1285 return 1; /* no error */
Neil Schemenauer48c70342001-08-09 15:38:31 +00001286}
1287
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001288PyDoc_STRVAR(gc_get_referrers__doc__,
Martin v. Löwis560da622001-11-24 09:24:51 +00001289"get_referrers(*objs) -> list\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001290Return the list of objects that directly refer to any of objs.");
Neil Schemenauer48c70342001-08-09 15:38:31 +00001291
Neil Schemenauer17e7be62001-08-10 14:46:47 +00001292static PyObject *
Martin v. Löwis560da622001-11-24 09:24:51 +00001293gc_get_referrers(PyObject *self, PyObject *args)
Neil Schemenauer48c70342001-08-09 15:38:31 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 int i;
1296 PyObject *result = PyList_New(0);
1297 if (!result) return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 for (i = 0; i < NUM_GENERATIONS; i++) {
1300 if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
1301 Py_DECREF(result);
1302 return NULL;
1303 }
1304 }
1305 return result;
Neil Schemenauer48c70342001-08-09 15:38:31 +00001306}
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001307
Tim Peters0f81ab62003-04-08 16:39:48 +00001308/* Append obj to list; return true if error (out of memory), false if OK. */
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001309static int
Tim Peters730f5532003-04-08 17:17:17 +00001310referentsvisit(PyObject *obj, PyObject *list)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001311{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return PyList_Append(list, obj) < 0;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001313}
1314
Tim Peters730f5532003-04-08 17:17:17 +00001315PyDoc_STRVAR(gc_get_referents__doc__,
1316"get_referents(*objs) -> list\n\
Jeremy Hylton059b0942003-04-03 16:29:13 +00001317Return the list of objects that are directly referred to by objs.");
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001318
1319static PyObject *
Tim Peters730f5532003-04-08 17:17:17 +00001320gc_get_referents(PyObject *self, PyObject *args)
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 Py_ssize_t i;
1323 PyObject *result = PyList_New(0);
Tim Peters0f81ab62003-04-08 16:39:48 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (result == NULL)
1326 return NULL;
Tim Peters0f81ab62003-04-08 16:39:48 +00001327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
1329 traverseproc traverse;
1330 PyObject *obj = PyTuple_GET_ITEM(args, i);
Tim Peters0f81ab62003-04-08 16:39:48 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (! PyObject_IS_GC(obj))
1333 continue;
1334 traverse = Py_TYPE(obj)->tp_traverse;
1335 if (! traverse)
1336 continue;
1337 if (traverse(obj, (visitproc)referentsvisit, result)) {
1338 Py_DECREF(result);
1339 return NULL;
1340 }
1341 }
1342 return result;
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001343}
1344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001345PyDoc_STRVAR(gc_get_objects__doc__,
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001346"get_objects() -> [...]\n"
1347"\n"
1348"Return a list of objects tracked by the collector (excluding the list\n"
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001349"returned).\n");
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001350
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001351static PyObject *
Tim Peters50c61d52003-04-06 01:50:50 +00001352gc_get_objects(PyObject *self, PyObject *noargs)
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 int i;
1355 PyObject* result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 result = PyList_New(0);
1358 if (result == NULL)
1359 return NULL;
1360 for (i = 0; i < NUM_GENERATIONS; i++) {
1361 if (append_objects(result, GEN_HEAD(i))) {
1362 Py_DECREF(result);
1363 return NULL;
1364 }
1365 }
1366 return result;
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001367}
1368
Antoine Pitroud4156c12012-10-30 22:43:19 +01001369PyDoc_STRVAR(gc_get_stats__doc__,
1370"get_stats() -> [...]\n"
1371"\n"
1372"Return a list of dictionaries containing per-generation statistics.\n");
1373
1374static PyObject *
1375gc_get_stats(PyObject *self, PyObject *noargs)
1376{
1377 int i;
1378 PyObject *result;
1379 struct gc_generation_stats stats[NUM_GENERATIONS], *st;
1380
1381 /* To get consistent values despite allocations while constructing
1382 the result list, we use a snapshot of the running stats. */
1383 for (i = 0; i < NUM_GENERATIONS; i++) {
1384 stats[i] = generation_stats[i];
1385 }
1386
1387 result = PyList_New(0);
1388 if (result == NULL)
1389 return NULL;
1390
1391 for (i = 0; i < NUM_GENERATIONS; i++) {
1392 PyObject *dict;
1393 st = &stats[i];
1394 dict = Py_BuildValue("{snsnsn}",
1395 "collections", st->collections,
1396 "collected", st->collected,
1397 "uncollectable", st->uncollectable
1398 );
1399 if (dict == NULL)
1400 goto error;
1401 if (PyList_Append(result, dict)) {
1402 Py_DECREF(dict);
1403 goto error;
1404 }
1405 Py_DECREF(dict);
1406 }
1407 return result;
1408
1409error:
1410 Py_XDECREF(result);
1411 return NULL;
1412}
1413
1414
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001415PyDoc_STRVAR(gc_is_tracked__doc__,
1416"is_tracked(obj) -> bool\n"
1417"\n"
1418"Returns true if the object is tracked by the garbage collector.\n"
1419"Simple atomic objects will return false.\n"
1420);
1421
1422static PyObject *
1423gc_is_tracked(PyObject *self, PyObject *obj)
1424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 PyObject *result;
1426
1427 if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
1428 result = Py_True;
1429 else
1430 result = Py_False;
1431 Py_INCREF(result);
1432 return result;
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001433}
1434
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001435
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001436PyDoc_STRVAR(gc__doc__,
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001437"This module provides access to the garbage collector for reference cycles.\n"
1438"\n"
Vladimir Marangozovf9d20c32000-08-06 22:45:31 +00001439"enable() -- Enable automatic garbage collection.\n"
1440"disable() -- Disable automatic garbage collection.\n"
1441"isenabled() -- Returns true if automatic collection is enabled.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001442"collect() -- Do a full collection right now.\n"
Thomas Wouters89f507f2006-12-13 04:49:30 +00001443"get_count() -- Return the current collection counts.\n"
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001444"set_debug() -- Set debugging flags.\n"
1445"get_debug() -- Get debugging flags.\n"
1446"set_threshold() -- Set the collection thresholds.\n"
1447"get_threshold() -- Return the current the collection thresholds.\n"
Neil Schemenauerc7c8d8e2001-08-09 15:58:59 +00001448"get_objects() -- Return a list of all objects tracked by the collector.\n"
Antoine Pitrou3a652b12009-03-23 18:52:06 +00001449"is_tracked() -- Returns true if a given object is tracked.\n"
Jeremy Hylton5bd378b2003-04-03 16:28:38 +00001450"get_referrers() -- Return the list of objects that refer to an object.\n"
Tim Peters730f5532003-04-08 17:17:17 +00001451"get_referents() -- Return the list of objects that an object refers to.\n");
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001452
1453static PyMethodDef GcMethods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
1455 {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
1456 {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
1457 {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
1458 {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
1459 {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
1460 {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
1461 {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
1462 {"collect", (PyCFunction)gc_collect,
1463 METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
1464 {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
Antoine Pitroud4156c12012-10-30 22:43:19 +01001465 {"get_stats", gc_get_stats, METH_NOARGS, gc_get_stats__doc__},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},
1467 {"get_referrers", gc_get_referrers, METH_VARARGS,
1468 gc_get_referrers__doc__},
1469 {"get_referents", gc_get_referents, METH_VARARGS,
1470 gc_get_referents__doc__},
1471 {NULL, NULL} /* Sentinel */
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001472};
1473
Martin v. Löwis1a214512008-06-11 05:26:20 +00001474static struct PyModuleDef gcmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyModuleDef_HEAD_INIT,
Antoine Pitrou696e0352010-08-08 22:18:46 +00001476 "gc", /* m_name */
1477 gc__doc__, /* m_doc */
1478 -1, /* m_size */
1479 GcMethods, /* m_methods */
1480 NULL, /* m_reload */
1481 NULL, /* m_traverse */
1482 NULL, /* m_clear */
1483 NULL /* m_free */
Martin v. Löwis1a214512008-06-11 05:26:20 +00001484};
1485
Jason Tishler6bc06ec2003-09-04 11:59:50 +00001486PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001487PyInit_gc(void)
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyObject *m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 m = PyModule_Create(&gcmodule);
Martin v. Löwis1a214512008-06-11 05:26:20 +00001492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (m == NULL)
1494 return NULL;
Tim Peters11558872003-04-06 23:30:52 +00001495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 if (garbage == NULL) {
1497 garbage = PyList_New(0);
1498 if (garbage == NULL)
1499 return NULL;
1500 }
1501 Py_INCREF(garbage);
1502 if (PyModule_AddObject(m, "garbage", garbage) < 0)
1503 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001504
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001505 if (callbacks == NULL) {
1506 callbacks = PyList_New(0);
1507 if (callbacks == NULL)
1508 return NULL;
1509 }
1510 Py_INCREF(callbacks);
1511 if (PyModule_AddObject(m, "callbacks", callbacks) < 0)
1512 return NULL;
1513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 /* Importing can't be done in collect() because collect()
1515 * can be called via PyGC_Collect() in Py_Finalize().
1516 * This wouldn't be a problem, except that <initialized> is
1517 * reset to 0 before calling collect which trips up
1518 * the import and triggers an assertion.
1519 */
1520 if (tmod == NULL) {
1521 tmod = PyImport_ImportModuleNoBlock("time");
1522 if (tmod == NULL)
1523 PyErr_Clear();
1524 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001525
Martin v. Löwis1a214512008-06-11 05:26:20 +00001526#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return NULL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 ADD_INT(DEBUG_STATS);
1528 ADD_INT(DEBUG_COLLECTABLE);
1529 ADD_INT(DEBUG_UNCOLLECTABLE);
1530 ADD_INT(DEBUG_SAVEALL);
1531 ADD_INT(DEBUG_LEAK);
Tim Peters11558872003-04-06 23:30:52 +00001532#undef ADD_INT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 return m;
Jeremy Hyltonc5007aa2000-06-30 05:02:53 +00001534}
1535
Guido van Rossume13ddc92003-04-17 17:29:22 +00001536/* API to invoke gc.collect() from C */
Neal Norwitz7b216c52006-03-04 20:01:53 +00001537Py_ssize_t
Guido van Rossume13ddc92003-04-17 17:29:22 +00001538PyGC_Collect(void)
1539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 Py_ssize_t n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 if (collecting)
1543 n = 0; /* already collecting, don't do anything */
1544 else {
1545 collecting = 1;
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001546 n = collect_with_callback(NUM_GENERATIONS - 1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 collecting = 0;
1548 }
Guido van Rossume13ddc92003-04-17 17:29:22 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 return n;
Guido van Rossume13ddc92003-04-17 17:29:22 +00001551}
1552
Antoine Pitroufef34e32013-05-19 01:11:58 +02001553Py_ssize_t
1554_PyGC_CollectNoFail(void)
1555{
1556 Py_ssize_t n;
1557
1558 /* This function should only be called on interpreter shutdown, and
1559 therefore not recursively. */
1560 assert(!collecting);
1561 collecting = 1;
1562 n = collect(NUM_GENERATIONS - 1, NULL, NULL, 1);
1563 collecting = 0;
1564 return n;
1565}
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001566
Antoine Pitrou696e0352010-08-08 22:18:46 +00001567void
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001568_PyGC_DumpShutdownStats(void)
Antoine Pitrou696e0352010-08-08 22:18:46 +00001569{
Antoine Pitrou2ed94eb2010-09-14 09:48:39 +00001570 if (!(debug & DEBUG_SAVEALL)
1571 && garbage != NULL && PyList_GET_SIZE(garbage) > 0) {
Georg Brandl08be72d2010-10-24 15:11:22 +00001572 char *message;
1573 if (debug & DEBUG_UNCOLLECTABLE)
Antoine Pitroub5d82042010-11-05 00:05:25 +00001574 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001575 "shutdown";
1576 else
Antoine Pitroub5d82042010-11-05 00:05:25 +00001577 message = "gc: %zd uncollectable objects at " \
Georg Brandl08be72d2010-10-24 15:11:22 +00001578 "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001579 /* PyErr_WarnFormat does too many things and we are at shutdown,
1580 the warnings module's dependencies (e.g. linecache) may be gone
1581 already. */
1582 if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
1583 "gc", NULL, message,
1584 PyList_GET_SIZE(garbage)))
Georg Brandl08be72d2010-10-24 15:11:22 +00001585 PyErr_WriteUnraisable(NULL);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001586 if (debug & DEBUG_UNCOLLECTABLE) {
1587 PyObject *repr = NULL, *bytes = NULL;
1588 repr = PyObject_Repr(garbage);
1589 if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
1590 PyErr_WriteUnraisable(garbage);
1591 else {
1592 PySys_WriteStderr(
Antoine Pitrou070cb3c2013-05-08 13:23:25 +02001593 " %s\n",
Antoine Pitrou696e0352010-08-08 22:18:46 +00001594 PyBytes_AS_STRING(bytes)
1595 );
1596 }
1597 Py_XDECREF(repr);
1598 Py_XDECREF(bytes);
1599 }
Antoine Pitrou696e0352010-08-08 22:18:46 +00001600 }
Antoine Pitrou5f454a02013-05-06 21:15:57 +02001601}
1602
1603void
1604_PyGC_Fini(void)
1605{
Kristján Valur Jónsson69c63522012-04-15 11:41:32 +00001606 Py_CLEAR(callbacks);
Antoine Pitrou696e0352010-08-08 22:18:46 +00001607}
1608
Neil Schemenauer43411b52001-08-30 00:05:51 +00001609/* for debugging */
Guido van Rossume13ddc92003-04-17 17:29:22 +00001610void
1611_PyGC_Dump(PyGC_Head *g)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 _PyObject_Dump(FROM_GC(g));
Neil Schemenauer43411b52001-08-30 00:05:51 +00001614}
1615
Neil Schemenauer43411b52001-08-30 00:05:51 +00001616/* extension modules might be compiled with GC support so these
1617 functions must always be available */
1618
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001619#undef PyObject_GC_Track
1620#undef PyObject_GC_UnTrack
1621#undef PyObject_GC_Del
1622#undef _PyObject_GC_Malloc
1623
Neil Schemenauer43411b52001-08-30 00:05:51 +00001624void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001625PyObject_GC_Track(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 _PyObject_GC_TRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001628}
1629
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001630/* for binary compatibility with 2.2 */
Neil Schemenauer43411b52001-08-30 00:05:51 +00001631void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001632_PyObject_GC_Track(PyObject *op)
1633{
1634 PyObject_GC_Track(op);
1635}
1636
1637void
1638PyObject_GC_UnTrack(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
1641 * call PyObject_GC_UnTrack twice on an object.
1642 */
1643 if (IS_TRACKED(op))
1644 _PyObject_GC_UNTRACK(op);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001645}
1646
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001647/* for binary compatibility with 2.2 */
1648void
1649_PyObject_GC_UnTrack(PyObject *op)
1650{
1651 PyObject_GC_UnTrack(op);
1652}
1653
Neil Schemenauer43411b52001-08-30 00:05:51 +00001654PyObject *
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001655_PyObject_GC_Malloc(size_t basicsize)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyObject *op;
1658 PyGC_Head *g;
1659 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1660 return PyErr_NoMemory();
1661 g = (PyGC_Head *)PyObject_MALLOC(
1662 sizeof(PyGC_Head) + basicsize);
1663 if (g == NULL)
1664 return PyErr_NoMemory();
1665 g->gc.gc_refs = GC_UNTRACKED;
1666 generations[0].count++; /* number of allocated GC objects */
1667 if (generations[0].count > generations[0].threshold &&
1668 enabled &&
1669 generations[0].threshold &&
1670 !collecting &&
1671 !PyErr_Occurred()) {
1672 collecting = 1;
1673 collect_generations();
1674 collecting = 0;
1675 }
1676 op = FROM_GC(g);
1677 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001678}
1679
1680PyObject *
1681_PyObject_GC_New(PyTypeObject *tp)
1682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
1684 if (op != NULL)
1685 op = PyObject_INIT(op, tp);
1686 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001687}
1688
1689PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001690_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001691{
Victor Stinner5d1866c2013-07-08 22:17:52 +02001692 size_t size;
1693 PyVarObject *op;
1694
1695 if (nitems < 0) {
1696 PyErr_BadInternalCall();
1697 return NULL;
1698 }
1699 size = _PyObject_VAR_SIZE(tp, nitems);
1700 op = (PyVarObject *) _PyObject_GC_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 if (op != NULL)
1702 op = PyObject_INIT_VAR(op, tp, nitems);
1703 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001704}
1705
1706PyVarObject *
Martin v. Löwis41290682006-02-16 14:56:14 +00001707_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
1710 PyGC_Head *g = AS_GC(op);
1711 if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
1712 return (PyVarObject *)PyErr_NoMemory();
1713 g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
1714 if (g == NULL)
1715 return (PyVarObject *)PyErr_NoMemory();
1716 op = (PyVarObject *) FROM_GC(g);
1717 Py_SIZE(op) = nitems;
1718 return op;
Neil Schemenauer43411b52001-08-30 00:05:51 +00001719}
1720
1721void
Neil Schemenauerfec4eb12002-04-12 02:41:03 +00001722PyObject_GC_Del(void *op)
Neil Schemenauer43411b52001-08-30 00:05:51 +00001723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 PyGC_Head *g = AS_GC(op);
1725 if (IS_TRACKED(op))
1726 gc_list_remove(g);
1727 if (generations[0].count > 0) {
1728 generations[0].count--;
1729 }
1730 PyObject_FREE(g);
Neil Schemenauer43411b52001-08-30 00:05:51 +00001731}