Line | Count | Source |
1 | | // This implements the reference cycle garbage collector. |
2 | | // The Python module interface to the collector is in gcmodule.c. |
3 | | // See InternalDocs/garbage_collector.md for more infromation. |
4 | | |
5 | | #include "Python.h" |
6 | | #include "pycore_ceval.h" // _Py_set_eval_breaker_bit() |
7 | | #include "pycore_dict.h" // _PyInlineValuesSize() |
8 | | #include "pycore_genobject.h" // _PyGen_FinalizerIsNoop() |
9 | | #include "pycore_initconfig.h" // _PyStatus_OK() |
10 | | #include "pycore_context.h" |
11 | | #include "pycore_interp.h" // PyInterpreterState.gc |
12 | | #include "pycore_interpframe.h" // _PyFrame_GetLocalsArray() |
13 | | #include "pycore_object.h" |
14 | | #include "pycore_object_alloc.h" // _PyObject_MallocWithType() |
15 | | #include "pycore_pyerrors.h" |
16 | | #include "pycore_pystate.h" // _PyThreadState_GET() |
17 | | #include "pycore_tuple.h" // _PyTuple_MaybeUntrack() |
18 | | #include "pycore_weakref.h" // _PyWeakref_ClearRef() |
19 | | #include "pydtrace.h" |
20 | | |
21 | | #if !defined(Py_GIL_DISABLED) |
22 | | |
23 | | typedef struct _gc_runtime_state GCState; |
24 | | |
25 | | #ifdef Py_DEBUG |
26 | | # define GC_DEBUG |
27 | | #endif |
28 | | |
29 | 1.21G | #define GC_NEXT _PyGCHead_NEXT |
30 | 118M | #define GC_PREV _PyGCHead_PREV |
31 | | |
32 | | // update_refs() set this bit for all objects in current generation. |
33 | | // subtract_refs() and move_unreachable() uses this to distinguish |
34 | | // visited object is in GCing or not. |
35 | | // |
36 | | // move_unreachable() removes this flag from reachable objects. |
37 | | // Only unreachable objects have this flag. |
38 | | // |
39 | | // No objects in interpreter have this flag after GC ends. |
40 | 2.38G | #define PREV_MASK_COLLECTING _PyGC_PREV_MASK_COLLECTING |
41 | | |
42 | | // Lowest bit of _gc_next is used for UNREACHABLE flag. |
43 | | // |
44 | | // This flag represents the object is in unreachable list in move_unreachable() |
45 | | // |
46 | | // Although this flag is used only in move_unreachable(), move_unreachable() |
47 | | // doesn't clear this flag to skip unnecessary iteration. |
48 | | // move_legacy_finalizers() removes this flag instead. |
49 | | // Between them, unreachable list is not normal list and we can not use |
50 | | // most gc_list_* functions for it. |
51 | 449M | #define NEXT_MASK_UNREACHABLE (1) |
52 | | |
53 | 2.77G | #define AS_GC(op) _Py_AS_GC(op) |
54 | 1.41G | #define FROM_GC(gc) _Py_FROM_GC(gc) |
55 | | |
56 | | // Automatically choose the generation that needs collecting. |
57 | 255k | #define GENERATION_AUTO (-1) |
58 | | |
59 | | static inline int |
60 | | gc_is_collecting(PyGC_Head *g) |
61 | 1.46G | { |
62 | 1.46G | return (g->_gc_prev & PREV_MASK_COLLECTING) != 0; |
63 | 1.46G | } |
64 | | |
65 | | static inline void |
66 | | gc_clear_collecting(PyGC_Head *g) |
67 | 461M | { |
68 | 461M | g->_gc_prev &= ~PREV_MASK_COLLECTING; |
69 | 461M | } |
70 | | |
71 | | static inline Py_ssize_t |
72 | | gc_get_refs(PyGC_Head *g) |
73 | 1.23G | { |
74 | 1.23G | return (Py_ssize_t)(g->_gc_prev >> _PyGC_PREV_SHIFT); |
75 | 1.23G | } |
76 | | |
77 | | static inline void |
78 | | gc_set_refs(PyGC_Head *g, Py_ssize_t refs) |
79 | 262M | { |
80 | 262M | g->_gc_prev = (g->_gc_prev & ~_PyGC_PREV_MASK) |
81 | 262M | | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT); |
82 | 262M | } |
83 | | |
84 | | static inline void |
85 | | gc_reset_refs(PyGC_Head *g, Py_ssize_t refs) |
86 | 466M | { |
87 | 466M | g->_gc_prev = (g->_gc_prev & _PyGC_PREV_MASK_FINALIZED) |
88 | 466M | | PREV_MASK_COLLECTING |
89 | 466M | | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT); |
90 | 466M | } |
91 | | |
92 | | static inline void |
93 | | gc_decref(PyGC_Head *g) |
94 | 387M | { |
95 | 387M | _PyObject_ASSERT_WITH_MSG(FROM_GC(g), |
96 | 387M | gc_get_refs(g) > 0, |
97 | 387M | "refcount is too small"); |
98 | 387M | g->_gc_prev -= 1 << _PyGC_PREV_SHIFT; |
99 | 387M | } |
100 | | |
101 | | |
102 | 239k | #define GEN_HEAD(gcstate, n) (&(gcstate)->generations[n].head) |
103 | | |
104 | | |
105 | | static GCState * |
106 | | get_gc_state(void) |
107 | 655M | { |
108 | 655M | PyInterpreterState *interp = _PyInterpreterState_GET(); |
109 | 655M | return &interp->gc; |
110 | 655M | } |
111 | | |
112 | | |
113 | | void |
114 | | _PyGC_InitState(GCState *gcstate) |
115 | 37 | { |
116 | 37 | #define INIT_HEAD(GEN) \ |
117 | 148 | do { \ |
118 | 148 | GEN.head._gc_next = (uintptr_t)&GEN.head; \ |
119 | 148 | GEN.head._gc_prev = (uintptr_t)&GEN.head; \ |
120 | 148 | } while (0) |
121 | | |
122 | 148 | for (int i = 0; i < NUM_GENERATIONS; i++) { |
123 | 111 | assert(gcstate->generations[i].count == 0); |
124 | 111 | INIT_HEAD(gcstate->generations[i]); |
125 | 111 | }; |
126 | 37 | gcstate->generation0 = GEN_HEAD(gcstate, 0); |
127 | 37 | INIT_HEAD(gcstate->permanent_generation); |
128 | | |
129 | 37 | #undef INIT_HEAD |
130 | 37 | } |
131 | | |
132 | | |
133 | | PyStatus |
134 | | _PyGC_Init(PyInterpreterState *interp) |
135 | 37 | { |
136 | 37 | GCState *gcstate = &interp->gc; |
137 | | |
138 | 37 | gcstate->generation_stats = PyMem_RawCalloc(1, sizeof(struct gc_stats)); |
139 | 37 | if (gcstate->generation_stats == NULL) { |
140 | 0 | return _PyStatus_NO_MEMORY(); |
141 | 0 | } |
142 | | |
143 | 37 | gcstate->garbage = PyList_New(0); |
144 | 37 | if (gcstate->garbage == NULL) { |
145 | 0 | return _PyStatus_NO_MEMORY(); |
146 | 0 | } |
147 | | |
148 | 37 | gcstate->callbacks = PyList_New(0); |
149 | 37 | if (gcstate->callbacks == NULL) { |
150 | 0 | return _PyStatus_NO_MEMORY(); |
151 | 0 | } |
152 | | |
153 | 37 | return _PyStatus_OK(); |
154 | 37 | } |
155 | | |
156 | | |
157 | | /* |
158 | | _gc_prev values |
159 | | --------------- |
160 | | |
161 | | Between collections, _gc_prev is used for doubly linked list. |
162 | | |
163 | | Lowest two bits of _gc_prev are used for flags. |
164 | | PREV_MASK_COLLECTING is used only while collecting and cleared before GC ends |
165 | | or _PyObject_GC_UNTRACK() is called. |
166 | | |
167 | | During a collection, _gc_prev is temporary used for gc_refs, and the gc list |
168 | | is singly linked until _gc_prev is restored. |
169 | | |
170 | | gc_refs |
171 | | At the start of a collection, update_refs() copies the true refcount |
172 | | to gc_refs, for each object in the generation being collected. |
173 | | subtract_refs() then adjusts gc_refs so that it equals the number of |
174 | | times an object is referenced directly from outside the generation |
175 | | being collected. |
176 | | |
177 | | PREV_MASK_COLLECTING |
178 | | Objects in generation being collected are marked PREV_MASK_COLLECTING in |
179 | | update_refs(). |
180 | | |
181 | | |
182 | | _gc_next values |
183 | | --------------- |
184 | | |
185 | | _gc_next takes these values: |
186 | | |
187 | | 0 |
188 | | The object is not tracked |
189 | | |
190 | | != 0 |
191 | | Pointer to the next object in the GC list. |
192 | | Additionally, lowest bit is used temporary for |
193 | | NEXT_MASK_UNREACHABLE flag described below. |
194 | | |
195 | | NEXT_MASK_UNREACHABLE |
196 | | move_unreachable() then moves objects not reachable (whether directly or |
197 | | indirectly) from outside the generation into an "unreachable" set and |
198 | | set this flag. |
199 | | |
200 | | Objects that are found to be reachable have gc_refs set to 1. |
201 | | When this flag is set for the reachable object, the object must be in |
202 | | "unreachable" set. |
203 | | The flag is unset and the object is moved back to "reachable" set. |
204 | | |
205 | | move_legacy_finalizers() will remove this flag from "unreachable" set. |
206 | | */ |
207 | | |
208 | | /*** list functions ***/ |
209 | | |
210 | | static inline void |
211 | | gc_list_init(PyGC_Head *list) |
212 | 996k | { |
213 | | // List header must not have flags. |
214 | | // We can assign pointer by simple cast. |
215 | 996k | list->_gc_prev = (uintptr_t)list; |
216 | 996k | list->_gc_next = (uintptr_t)list; |
217 | 996k | } |
218 | | |
219 | | static inline int |
220 | | gc_list_is_empty(PyGC_Head *list) |
221 | 10.2M | { |
222 | 10.2M | return (list->_gc_next == (uintptr_t)list); |
223 | 10.2M | } |
224 | | |
225 | | /* Append `node` to `list`. */ |
226 | | static inline void |
227 | | gc_list_append(PyGC_Head *node, PyGC_Head *list) |
228 | 49.5M | { |
229 | 49.5M | PyGC_Head *last = (PyGC_Head *)list->_gc_prev; |
230 | | |
231 | | // last <-> node |
232 | 49.5M | _PyGCHead_SET_PREV(node, last); |
233 | 49.5M | _PyGCHead_SET_NEXT(last, node); |
234 | | |
235 | | // node <-> list |
236 | 49.5M | _PyGCHead_SET_NEXT(node, list); |
237 | 49.5M | list->_gc_prev = (uintptr_t)node; |
238 | 49.5M | } |
239 | | |
240 | | /* Remove `node` from the gc list it's currently in. */ |
241 | | static inline void |
242 | | gc_list_remove(PyGC_Head *node) |
243 | 0 | { |
244 | 0 | PyGC_Head *prev = GC_PREV(node); |
245 | 0 | PyGC_Head *next = GC_NEXT(node); |
246 | |
|
247 | 0 | _PyGCHead_SET_NEXT(prev, next); |
248 | 0 | _PyGCHead_SET_PREV(next, prev); |
249 | |
|
250 | 0 | node->_gc_next = 0; /* object is not currently tracked */ |
251 | 0 | } |
252 | | |
253 | | /* Move `node` from the gc list it's currently in (which is not explicitly |
254 | | * named here) to the end of `list`. This is semantically the same as |
255 | | * gc_list_remove(node) followed by gc_list_append(node, list). |
256 | | */ |
257 | | static void |
258 | | gc_list_move(PyGC_Head *node, PyGC_Head *list) |
259 | 8.85M | { |
260 | | /* Unlink from current list. */ |
261 | 8.85M | PyGC_Head *from_prev = GC_PREV(node); |
262 | 8.85M | PyGC_Head *from_next = GC_NEXT(node); |
263 | 8.85M | _PyGCHead_SET_NEXT(from_prev, from_next); |
264 | 8.85M | _PyGCHead_SET_PREV(from_next, from_prev); |
265 | | |
266 | | /* Relink at end of new list. */ |
267 | | // list must not have flags. So we can skip macros. |
268 | 8.85M | PyGC_Head *to_prev = (PyGC_Head*)list->_gc_prev; |
269 | 8.85M | _PyGCHead_SET_PREV(node, to_prev); |
270 | 8.85M | _PyGCHead_SET_NEXT(to_prev, node); |
271 | 8.85M | list->_gc_prev = (uintptr_t)node; |
272 | 8.85M | _PyGCHead_SET_NEXT(node, list); |
273 | 8.85M | } |
274 | | |
275 | | /* append list `from` onto list `to`; `from` becomes an empty list */ |
276 | | static void |
277 | | gc_list_merge(PyGC_Head *from, PyGC_Head *to) |
278 | 448k | { |
279 | 448k | assert(from != to); |
280 | 448k | if (!gc_list_is_empty(from)) { |
281 | 116k | PyGC_Head *to_tail = GC_PREV(to); |
282 | 116k | PyGC_Head *from_head = GC_NEXT(from); |
283 | 116k | PyGC_Head *from_tail = GC_PREV(from); |
284 | 116k | assert(from_head != from); |
285 | 116k | assert(from_tail != from); |
286 | | |
287 | 116k | _PyGCHead_SET_NEXT(to_tail, from_head); |
288 | 116k | _PyGCHead_SET_PREV(from_head, to_tail); |
289 | | |
290 | 116k | _PyGCHead_SET_NEXT(from_tail, to); |
291 | 116k | _PyGCHead_SET_PREV(to, from_tail); |
292 | 116k | } |
293 | 448k | gc_list_init(from); |
294 | 448k | } |
295 | | |
296 | | static Py_ssize_t |
297 | | gc_list_size(PyGC_Head *list) |
298 | 109k | { |
299 | 109k | PyGC_Head *gc; |
300 | 109k | Py_ssize_t n = 0; |
301 | 6.79M | for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) { |
302 | 6.68M | n++; |
303 | 6.68M | } |
304 | 109k | return n; |
305 | 109k | } |
306 | | |
307 | | /* Walk the list and mark all objects as non-collecting */ |
308 | | static inline void |
309 | | gc_list_clear_collecting(PyGC_Head *collectable) |
310 | 1.70k | { |
311 | 1.70k | PyGC_Head *gc; |
312 | 4.02M | for (gc = GC_NEXT(collectable); gc != collectable; gc = GC_NEXT(gc)) { |
313 | 4.02M | gc_clear_collecting(gc); |
314 | 4.02M | } |
315 | 1.70k | } |
316 | | |
317 | | /* Append objects in a GC list to a Python list. |
318 | | * Return 0 if all OK, < 0 if error (out of memory for list) |
319 | | */ |
320 | | static int |
321 | | append_objects(PyObject *py_list, PyGC_Head *gc_list) |
322 | 0 | { |
323 | 0 | PyGC_Head *gc; |
324 | 0 | for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) { |
325 | 0 | PyObject *op = FROM_GC(gc); |
326 | 0 | if (op != py_list) { |
327 | 0 | if (PyList_Append(py_list, op)) { |
328 | 0 | return -1; /* exception */ |
329 | 0 | } |
330 | 0 | } |
331 | 0 | } |
332 | 0 | return 0; |
333 | 0 | } |
334 | | |
335 | | // Constants for validate_list's flags argument. |
336 | | enum flagstates {collecting_clear_unreachable_clear, |
337 | | collecting_clear_unreachable_set, |
338 | | collecting_set_unreachable_clear, |
339 | | collecting_set_unreachable_set}; |
340 | | |
341 | | #ifdef GC_DEBUG |
342 | | // validate_list checks list consistency. And it works as document |
343 | | // describing when flags are expected to be set / unset. |
344 | | // `head` must be a doubly-linked gc list, although it's fine (expected!) if |
345 | | // the prev and next pointers are "polluted" with flags. |
346 | | // What's checked: |
347 | | // - The `head` pointers are not polluted. |
348 | | // - The objects' PREV_MASK_COLLECTING and NEXT_MASK_UNREACHABLE flags are all |
349 | | // `set or clear, as specified by the 'flags' argument. |
350 | | // - The prev and next pointers are mutually consistent. |
351 | | static void |
352 | | validate_list(PyGC_Head *head, enum flagstates flags) |
353 | | { |
354 | | assert((head->_gc_prev & PREV_MASK_COLLECTING) == 0); |
355 | | assert((head->_gc_next & NEXT_MASK_UNREACHABLE) == 0); |
356 | | uintptr_t prev_value = 0, next_value = 0; |
357 | | switch (flags) { |
358 | | case collecting_clear_unreachable_clear: |
359 | | break; |
360 | | case collecting_set_unreachable_clear: |
361 | | prev_value = PREV_MASK_COLLECTING; |
362 | | break; |
363 | | case collecting_clear_unreachable_set: |
364 | | next_value = NEXT_MASK_UNREACHABLE; |
365 | | break; |
366 | | case collecting_set_unreachable_set: |
367 | | prev_value = PREV_MASK_COLLECTING; |
368 | | next_value = NEXT_MASK_UNREACHABLE; |
369 | | break; |
370 | | default: |
371 | | assert(! "bad internal flags argument"); |
372 | | } |
373 | | PyGC_Head *prev = head; |
374 | | PyGC_Head *gc = GC_NEXT(head); |
375 | | while (gc != head) { |
376 | | PyGC_Head *trueprev = GC_PREV(gc); |
377 | | PyGC_Head *truenext = (PyGC_Head *)(gc->_gc_next & ~NEXT_MASK_UNREACHABLE); |
378 | | assert(truenext != NULL); |
379 | | assert(trueprev == prev); |
380 | | assert((gc->_gc_prev & PREV_MASK_COLLECTING) == prev_value); |
381 | | assert((gc->_gc_next & NEXT_MASK_UNREACHABLE) == next_value); |
382 | | prev = gc; |
383 | | gc = truenext; |
384 | | } |
385 | | assert(prev == GC_PREV(head)); |
386 | | } |
387 | | #else |
388 | 993k | #define validate_list(x, y) do{}while(0) |
389 | | #endif |
390 | | |
391 | | /*** end of list stuff ***/ |
392 | | |
393 | | |
394 | | /* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 and |
395 | | * PREV_MASK_COLLECTING bit is set for all objects in containers. |
396 | | */ |
397 | | static Py_ssize_t |
398 | | update_refs(PyGC_Head *containers) |
399 | 111k | { |
400 | 111k | PyGC_Head *next; |
401 | 111k | PyGC_Head *gc = GC_NEXT(containers); |
402 | 111k | Py_ssize_t candidates = 0; |
403 | | |
404 | 466M | while (gc != containers) { |
405 | 466M | next = GC_NEXT(gc); |
406 | 466M | PyObject *op = FROM_GC(gc); |
407 | 466M | if (_Py_IsImmortal(op)) { |
408 | 0 | assert(!_Py_IsStaticImmortal(op)); |
409 | 0 | _PyObject_GC_UNTRACK(op); |
410 | 0 | gc = next; |
411 | 0 | continue; |
412 | 0 | } |
413 | 466M | gc_reset_refs(gc, Py_REFCNT(op)); |
414 | | /* Python's cyclic gc should never see an incoming refcount |
415 | | * of 0: if something decref'ed to 0, it should have been |
416 | | * deallocated immediately at that time. |
417 | | * Possible cause (if the assert triggers): a tp_dealloc |
418 | | * routine left a gc-aware object tracked during its teardown |
419 | | * phase, and did something-- or allowed something to happen -- |
420 | | * that called back into Python. gc can trigger then, and may |
421 | | * see the still-tracked dying object. Before this assert |
422 | | * was added, such mistakes went on to allow gc to try to |
423 | | * delete the object again. In a debug build, that caused |
424 | | * a mysterious segfault, when _Py_ForgetReference tried |
425 | | * to remove the object from the doubly-linked list of all |
426 | | * objects a second time. In a release build, an actual |
427 | | * double deallocation occurred, which leads to corruption |
428 | | * of the allocator's internal bookkeeping pointers. That's |
429 | | * so serious that maybe this should be a release-build |
430 | | * check instead of an assert? |
431 | | */ |
432 | 466M | _PyObject_ASSERT(op, gc_get_refs(gc) != 0); |
433 | 466M | gc = next; |
434 | 466M | candidates++; |
435 | 466M | } |
436 | 111k | return candidates; |
437 | 111k | } |
438 | | |
439 | | /* A traversal callback for subtract_refs. */ |
440 | | static int |
441 | | visit_decref(PyObject *op, void *parent) |
442 | 1.68G | { |
443 | 1.68G | OBJECT_STAT_INC(object_visits); |
444 | 1.68G | _PyObject_ASSERT(_PyObject_CAST(parent), !_PyObject_IsFreed(op)); |
445 | | |
446 | 1.68G | if (_PyObject_IS_GC(op)) { |
447 | 739M | PyGC_Head *gc = AS_GC(op); |
448 | | /* We're only interested in gc_refs for objects in the |
449 | | * generation being collected, which can be recognized |
450 | | * because only they have positive gc_refs. |
451 | | */ |
452 | 739M | if (gc_is_collecting(gc)) { |
453 | 387M | gc_decref(gc); |
454 | 387M | } |
455 | 739M | } |
456 | 1.68G | return 0; |
457 | 1.68G | } |
458 | | |
459 | | int |
460 | | _PyGC_VisitStackRef(_PyStackRef *ref, visitproc visit, void *arg) |
461 | 3.93M | { |
462 | | // This is a bit tricky! We want to ignore stackrefs with embedded |
463 | | // refcounts when computing the incoming references, but otherwise treat |
464 | | // them like normal. |
465 | 3.93M | assert(!PyStackRef_IsTaggedInt(*ref)); |
466 | 3.93M | if (!PyStackRef_RefcountOnObject(*ref) && (visit == visit_decref)) { |
467 | 212k | return 0; |
468 | 212k | } |
469 | 3.71M | Py_VISIT(PyStackRef_AsPyObjectBorrow(*ref)); |
470 | 3.71M | return 0; |
471 | 3.71M | } |
472 | | |
473 | | int |
474 | | _PyGC_VisitFrameStack(_PyInterpreterFrame *frame, visitproc visit, void *arg) |
475 | 682k | { |
476 | 682k | _PyStackRef *ref = _PyFrame_GetLocalsArray(frame); |
477 | | /* locals and stack */ |
478 | 4.62M | for (; ref < frame->stackpointer; ref++) { |
479 | 3.94M | if (!PyStackRef_IsTaggedInt(*ref)) { |
480 | 3.93M | _Py_VISIT_STACKREF(*ref); |
481 | 3.93M | } |
482 | 3.94M | } |
483 | 682k | return 0; |
484 | 682k | } |
485 | | |
486 | | /* Subtract internal references from gc_refs. After this, gc_refs is >= 0 |
487 | | * for all objects in containers. The ones with gc_refs > 0 are directly |
488 | | * reachable from outside containers, and so can't be collected. |
489 | | */ |
490 | | static void |
491 | | subtract_refs(PyGC_Head *containers) |
492 | 111k | { |
493 | 111k | traverseproc traverse; |
494 | 111k | PyGC_Head *gc = GC_NEXT(containers); |
495 | 466M | for (; gc != containers; gc = GC_NEXT(gc)) { |
496 | 466M | PyObject *op = FROM_GC(gc); |
497 | 466M | traverse = Py_TYPE(op)->tp_traverse; |
498 | 466M | (void) traverse(op, |
499 | 466M | visit_decref, |
500 | 466M | op); |
501 | 466M | } |
502 | 111k | } |
503 | | |
504 | | /* A traversal callback for move_unreachable. */ |
505 | | static int |
506 | | visit_reachable(PyObject *op, void *arg) |
507 | 1.64G | { |
508 | 1.64G | PyGC_Head *reachable = arg; |
509 | 1.64G | OBJECT_STAT_INC(object_visits); |
510 | 1.64G | if (!_PyObject_IS_GC(op)) { |
511 | 926M | return 0; |
512 | 926M | } |
513 | | |
514 | 720M | PyGC_Head *gc = AS_GC(op); |
515 | 720M | const Py_ssize_t gc_refs = gc_get_refs(gc); |
516 | | |
517 | | // Ignore objects in other generation. |
518 | | // This also skips objects "to the left" of the current position in |
519 | | // move_unreachable's scan of the 'young' list - they've already been |
520 | | // traversed, and no longer have the PREV_MASK_COLLECTING flag. |
521 | 720M | if (! gc_is_collecting(gc)) { |
522 | 452M | return 0; |
523 | 452M | } |
524 | | // It would be a logic error elsewhere if the collecting flag were set on |
525 | | // an untracked object. |
526 | 268M | _PyObject_ASSERT(op, gc->_gc_next != 0); |
527 | | |
528 | 268M | if (gc->_gc_next & NEXT_MASK_UNREACHABLE) { |
529 | | /* This had gc_refs = 0 when move_unreachable got |
530 | | * to it, but turns out it's reachable after all. |
531 | | * Move it back to move_unreachable's 'young' list, |
532 | | * and move_unreachable will eventually get to it |
533 | | * again. |
534 | | */ |
535 | | // Manually unlink gc from unreachable list because the list functions |
536 | | // don't work right in the presence of NEXT_MASK_UNREACHABLE flags. |
537 | 49.5M | PyGC_Head *prev = GC_PREV(gc); |
538 | 49.5M | PyGC_Head *next = (PyGC_Head*)(gc->_gc_next & ~NEXT_MASK_UNREACHABLE); |
539 | 49.5M | _PyObject_ASSERT(FROM_GC(prev), |
540 | 49.5M | prev->_gc_next & NEXT_MASK_UNREACHABLE); |
541 | 49.5M | _PyObject_ASSERT(FROM_GC(next), |
542 | 49.5M | next->_gc_next & NEXT_MASK_UNREACHABLE); |
543 | 49.5M | prev->_gc_next = gc->_gc_next; // copy NEXT_MASK_UNREACHABLE |
544 | 49.5M | _PyGCHead_SET_PREV(next, prev); |
545 | | |
546 | 49.5M | gc_list_append(gc, reachable); |
547 | 49.5M | gc_set_refs(gc, 1); |
548 | 49.5M | } |
549 | 218M | else if (gc_refs == 0) { |
550 | | /* This is in move_unreachable's 'young' list, but |
551 | | * the traversal hasn't yet gotten to it. All |
552 | | * we need to do is tell move_unreachable that it's |
553 | | * reachable. |
554 | | */ |
555 | 212M | gc_set_refs(gc, 1); |
556 | 212M | } |
557 | | /* Else there's nothing to do. |
558 | | * If gc_refs > 0, it must be in move_unreachable's 'young' |
559 | | * list, and move_unreachable will eventually get to it. |
560 | | */ |
561 | 5.79M | else { |
562 | 5.79M | _PyObject_ASSERT_WITH_MSG(op, gc_refs > 0, "refcount is too small"); |
563 | 5.79M | } |
564 | 268M | return 0; |
565 | 720M | } |
566 | | |
567 | | /* Move the unreachable objects from young to unreachable. After this, |
568 | | * all objects in young don't have PREV_MASK_COLLECTING flag and |
569 | | * unreachable have the flag. |
570 | | * All objects in young after this are directly or indirectly reachable |
571 | | * from outside the original young; and all objects in unreachable are |
572 | | * not. |
573 | | * |
574 | | * This function restores _gc_prev pointer. young and unreachable are |
575 | | * doubly linked list after this function. |
576 | | * But _gc_next in unreachable list has NEXT_MASK_UNREACHABLE flag. |
577 | | * So we can not gc_list_* functions for unreachable until we remove the flag. |
578 | | */ |
579 | | static Py_ssize_t |
580 | | move_unreachable(PyGC_Head *young, PyGC_Head *unreachable) |
581 | 111k | { |
582 | 111k | Py_ssize_t reachable = 0; |
583 | | // previous elem in the young list, used for restore gc_prev. |
584 | 111k | PyGC_Head *prev = young; |
585 | 111k | PyGC_Head *gc = GC_NEXT(young); |
586 | | |
587 | | /* Invariants: all objects "to the left" of us in young are reachable |
588 | | * (directly or indirectly) from outside the young list as it was at entry. |
589 | | * |
590 | | * All other objects from the original young "to the left" of us are in |
591 | | * unreachable now, and have NEXT_MASK_UNREACHABLE. All objects to the |
592 | | * left of us in 'young' now have been scanned, and no objects here |
593 | | * or to the right have been scanned yet. |
594 | | */ |
595 | | |
596 | 515M | while (gc != young) { |
597 | 515M | if (gc_get_refs(gc)) { |
598 | | /* gc is definitely reachable from outside the |
599 | | * original 'young'. Mark it as such, and traverse |
600 | | * its pointers to find any other objects that may |
601 | | * be directly reachable from it. Note that the |
602 | | * call to tp_traverse may append objects to young, |
603 | | * so we have to wait until it returns to determine |
604 | | * the next object to visit. |
605 | | */ |
606 | 455M | PyObject *op = FROM_GC(gc); |
607 | 455M | traverseproc traverse = Py_TYPE(op)->tp_traverse; |
608 | 455M | _PyObject_ASSERT_WITH_MSG(op, gc_get_refs(gc) > 0, |
609 | 455M | "refcount is too small"); |
610 | | // NOTE: visit_reachable may change gc->_gc_next when |
611 | | // young->_gc_prev == gc. Don't do gc = GC_NEXT(gc) before! |
612 | 455M | (void) traverse(op, |
613 | 455M | visit_reachable, |
614 | 455M | (void *)young); |
615 | | // relink gc_prev to prev element. |
616 | 455M | _PyGCHead_SET_PREV(gc, prev); |
617 | | // gc is not COLLECTING state after here. |
618 | 455M | gc_clear_collecting(gc); |
619 | 455M | if (PyTuple_CheckExact(op)) { |
620 | | // Untracking gc overwrites the gc_refs of the next object. |
621 | 235M | PyGC_Head *next = GC_NEXT(gc); |
622 | 235M | uintptr_t next_refs = next->_gc_prev; |
623 | 235M | _PyTuple_MaybeUntrack(op); |
624 | 235M | next->_gc_prev = next_refs; |
625 | 235M | if (gc->_gc_next != 0) { |
626 | 218M | prev = gc; |
627 | 218M | reachable++; |
628 | 218M | } |
629 | 235M | } |
630 | 219M | else { |
631 | 219M | prev = gc; |
632 | 219M | reachable++; |
633 | 219M | } |
634 | 455M | } |
635 | 60.2M | else { |
636 | | /* This *may* be unreachable. To make progress, |
637 | | * assume it is. gc isn't directly reachable from |
638 | | * any object we've already traversed, but may be |
639 | | * reachable from an object we haven't gotten to yet. |
640 | | * visit_reachable will eventually move gc back into |
641 | | * young if that's so, and we'll see it again. |
642 | | */ |
643 | | // Move gc to unreachable. |
644 | | // No need to gc->next->prev = prev because it is single linked. |
645 | 60.2M | prev->_gc_next = gc->_gc_next; |
646 | | |
647 | | // We can't use gc_list_append() here because we use |
648 | | // NEXT_MASK_UNREACHABLE here. |
649 | 60.2M | PyGC_Head *last = GC_PREV(unreachable); |
650 | | // NOTE: Since all objects in unreachable set has |
651 | | // NEXT_MASK_UNREACHABLE flag, we set it unconditionally. |
652 | | // But this may pollute the unreachable list head's 'next' pointer |
653 | | // too. That's semantically senseless but expedient here - the |
654 | | // damage is repaired when this function ends. |
655 | 60.2M | last->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)gc); |
656 | 60.2M | _PyGCHead_SET_PREV(gc, last); |
657 | 60.2M | gc->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)unreachable); |
658 | 60.2M | unreachable->_gc_prev = (uintptr_t)gc; |
659 | 60.2M | } |
660 | 515M | gc = (PyGC_Head*)prev->_gc_next; |
661 | 515M | } |
662 | | // young->_gc_prev must be last element remained in the list. |
663 | 111k | young->_gc_prev = (uintptr_t)prev; |
664 | | // don't let the pollution of the list head's next pointer leak |
665 | 111k | unreachable->_gc_next &= ~NEXT_MASK_UNREACHABLE; |
666 | 111k | return reachable; |
667 | 111k | } |
668 | | |
669 | | /* Return true if object has a pre-PEP 442 finalization method. */ |
670 | | static int |
671 | | has_legacy_finalizer(PyObject *op) |
672 | 6.68M | { |
673 | 6.68M | return Py_TYPE(op)->tp_del != NULL; |
674 | 6.68M | } |
675 | | |
676 | | /* Move the objects in unreachable with tp_del slots into `finalizers`. |
677 | | * |
678 | | * This function also removes NEXT_MASK_UNREACHABLE flag |
679 | | * from _gc_next in unreachable. |
680 | | */ |
681 | | static void |
682 | | move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers) |
683 | 109k | { |
684 | 109k | PyGC_Head *gc, *next; |
685 | 109k | _PyObject_ASSERT( |
686 | 109k | FROM_GC(unreachable), |
687 | 109k | (unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0); |
688 | | |
689 | | /* March over unreachable. Move objects with finalizers into |
690 | | * `finalizers`. |
691 | | */ |
692 | 6.79M | for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) { |
693 | 6.68M | PyObject *op = FROM_GC(gc); |
694 | | |
695 | 6.68M | _PyObject_ASSERT(op, gc->_gc_next & NEXT_MASK_UNREACHABLE); |
696 | 6.68M | gc->_gc_next &= ~NEXT_MASK_UNREACHABLE; |
697 | 6.68M | next = (PyGC_Head*)gc->_gc_next; |
698 | | |
699 | 6.68M | if (has_legacy_finalizer(op)) { |
700 | 0 | gc_clear_collecting(gc); |
701 | 0 | gc_list_move(gc, finalizers); |
702 | 0 | } |
703 | 6.68M | } |
704 | 109k | } |
705 | | |
706 | | static inline void |
707 | | clear_unreachable_mask(PyGC_Head *unreachable) |
708 | 1.70k | { |
709 | | /* Check that the list head does not have the unreachable bit set */ |
710 | 1.70k | _PyObject_ASSERT( |
711 | 1.70k | FROM_GC(unreachable), |
712 | 1.70k | ((uintptr_t)unreachable & NEXT_MASK_UNREACHABLE) == 0); |
713 | 1.70k | _PyObject_ASSERT( |
714 | 1.70k | FROM_GC(unreachable), |
715 | 1.70k | (unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0); |
716 | | |
717 | 1.70k | PyGC_Head *gc, *next; |
718 | 4.02M | for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) { |
719 | 4.02M | _PyObject_ASSERT((PyObject*)FROM_GC(gc), gc->_gc_next & NEXT_MASK_UNREACHABLE); |
720 | 4.02M | gc->_gc_next &= ~NEXT_MASK_UNREACHABLE; |
721 | 4.02M | next = (PyGC_Head*)gc->_gc_next; |
722 | 4.02M | } |
723 | 1.70k | validate_list(unreachable, collecting_set_unreachable_clear); |
724 | 1.70k | } |
725 | | |
726 | | /* A traversal callback for move_legacy_finalizer_reachable. */ |
727 | | static int |
728 | | visit_move(PyObject *op, void *arg) |
729 | 0 | { |
730 | 0 | PyGC_Head *tolist = arg; |
731 | 0 | OBJECT_STAT_INC(object_visits); |
732 | 0 | if (_PyObject_IS_GC(op)) { |
733 | 0 | PyGC_Head *gc = AS_GC(op); |
734 | 0 | if (gc_is_collecting(gc)) { |
735 | 0 | gc_list_move(gc, tolist); |
736 | 0 | gc_clear_collecting(gc); |
737 | 0 | } |
738 | 0 | } |
739 | 0 | return 0; |
740 | 0 | } |
741 | | |
742 | | /* Move objects that are reachable from finalizers, from the unreachable set |
743 | | * into finalizers set. |
744 | | */ |
745 | | static void |
746 | | move_legacy_finalizer_reachable(PyGC_Head *finalizers) |
747 | 109k | { |
748 | 109k | traverseproc traverse; |
749 | 109k | PyGC_Head *gc = GC_NEXT(finalizers); |
750 | 109k | for (; gc != finalizers; gc = GC_NEXT(gc)) { |
751 | | /* Note that the finalizers list may grow during this. */ |
752 | 0 | traverse = Py_TYPE(FROM_GC(gc))->tp_traverse; |
753 | 0 | (void) traverse(FROM_GC(gc), |
754 | 0 | visit_move, |
755 | 0 | (void *)finalizers); |
756 | 0 | } |
757 | 109k | } |
758 | | |
759 | | /* Handle weakref callbacks. Note that it's possible for such weakrefs to be |
760 | | * outside the unreachable set -- indeed, those are precisely the weakrefs |
761 | | * whose callbacks must be invoked. See gc_weakref.txt for overview & some |
762 | | * details. |
763 | | * |
764 | | * The clearing of weakrefs is suble and must be done carefully, as there was |
765 | | * previous bugs related to this. First, weakrefs to the unreachable set of |
766 | | * objects must be cleared before we start calling `tp_clear`. If we don't, |
767 | | * those weakrefs can reveal unreachable objects to Python-level code and that |
768 | | * is not safe. Many objects are not usable after `tp_clear` has been called |
769 | | * and could even cause crashes if accessed (see bpo-38006 and gh-91636 as |
770 | | * example bugs). |
771 | | * |
772 | | * Weakrefs with callbacks always need to be cleared before executing the |
773 | | * callback. That's because sometimes a callback will call the ref object, |
774 | | * to check if the reference is actually dead (KeyedRef does this, for |
775 | | * example). We want to indicate that it is dead, even though it is possible |
776 | | * a finalizer might resurrect it. Clearing also prevents the callback from |
777 | | * executing more than once. |
778 | | * |
779 | | * Since Python 2.3, all weakrefs to cyclic garbage have been cleared *before* |
780 | | * calling finalizers. However, since tp_subclasses started being necessary |
781 | | * to invalidate caches (e.g. by PyType_Modified), that clearing has created |
782 | | * a bug. If the weakref to the subclass is cleared before a finalizer is |
783 | | * called, the cache may not be correctly invalidated. That can lead to |
784 | | * segfaults since the caches can refer to deallocated objects (GH-135552 |
785 | | * is an example). Now, we delay the clear of weakrefs without callbacks |
786 | | * until *after* finalizers have been executed. That means weakrefs without |
787 | | * callbacks are still usable while finalizers are being executed. |
788 | | * |
789 | | * The weakrefs that are inside the unreachable set must also be cleared. |
790 | | * The reason this is required is not immediately obvious. If the weakref |
791 | | * refers to an object outside of the unreachable set, that object might go |
792 | | * away when we start clearing objects. Normally, the object should also be |
793 | | * part of the unreachable set but that's not true in the case of incomplete |
794 | | * or missing `tp_traverse` methods. When that object goes away, the callback |
795 | | * for weakref can be executed and that could reveal unreachable objects to |
796 | | * Python-level code. See bpo-38006 as an example bug. |
797 | | */ |
798 | | static int |
799 | | handle_weakref_callbacks(PyGC_Head *unreachable, PyGC_Head *old, |
800 | | bool *needs_resurrection_check) |
801 | 109k | { |
802 | 109k | PyGC_Head *gc; |
803 | 109k | PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */ |
804 | 109k | PyGC_Head *next; |
805 | 109k | int num_freed = 0; |
806 | | |
807 | 109k | gc_list_init(&wrcb_to_call); |
808 | | |
809 | | /* Find all weakrefs with callbacks and move into `wrcb_to_call` if the |
810 | | * callback needs to be invoked. We make another pass over wrcb_to_call, |
811 | | * invoking callbacks, after this pass completes. |
812 | | */ |
813 | 6.79M | for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) { |
814 | 6.68M | PyWeakReference **wrlist; |
815 | | |
816 | 6.68M | PyObject *op = FROM_GC(gc); |
817 | 6.68M | next = GC_NEXT(gc); |
818 | | |
819 | 6.68M | if (! _PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) { |
820 | 4.83M | continue; |
821 | 4.83M | } |
822 | | |
823 | | /* It supports weakrefs. Does it have any? |
824 | | * |
825 | | * This is never triggered for static types so we can avoid the |
826 | | * (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR(). |
827 | | */ |
828 | 1.84M | wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op); |
829 | | |
830 | | /* `op` may have some weakrefs. March over the list and move the |
831 | | * weakrefs with callbacks that must be called into wrcb_to_call. |
832 | | */ |
833 | 1.84M | PyWeakReference *next_wr; |
834 | 2.08M | for (PyWeakReference *wr = *wrlist; wr != NULL; wr = next_wr) { |
835 | | // Get the next list element to get iterator progress if we omit |
836 | | // clearing of the weakref (because _PyWeakref_ClearRef changes |
837 | | // next pointer in the wrlist). |
838 | 233k | next_wr = wr->wr_next; |
839 | | |
840 | 233k | if (wr->wr_callback == NULL) { |
841 | | /* no callback */ |
842 | 212k | continue; |
843 | 212k | } |
844 | | |
845 | | // Clear the weakref. See the comments above this function for |
846 | | // reasons why we need to clear weakrefs that have callbacks. |
847 | | // Note that _PyWeakref_ClearRef clears the weakref but leaves the |
848 | | // callback pointer intact. Obscure: it also changes *wrlist. |
849 | 20.7k | _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op); |
850 | 20.7k | _PyWeakref_ClearRef(wr); |
851 | 20.7k | _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None); |
852 | | |
853 | | /* Headache time. `op` is going away, and is weakly referenced by |
854 | | * `wr`, which has a callback. Should the callback be invoked? If wr |
855 | | * is also trash, no: |
856 | | * |
857 | | * 1. There's no need to call it. The object and the weakref are |
858 | | * both going away, so it's legitimate to pretend the weakref is |
859 | | * going away first. The user has to ensure a weakref outlives its |
860 | | * referent if they want a guarantee that the wr callback will get |
861 | | * invoked. |
862 | | * |
863 | | * 2. It may be catastrophic to call it. If the callback is also in |
864 | | * cyclic trash (CT), then although the CT is unreachable from |
865 | | * outside the current generation, CT may be reachable from the |
866 | | * callback. Then the callback could resurrect insane objects. |
867 | | * |
868 | | * Since the callback is never needed and may be unsafe in this |
869 | | * case, wr is simply left in the unreachable set. Note that |
870 | | * clear_weakrefs() will ensure its callback will not trigger |
871 | | * inside delete_garbage(). |
872 | | * |
873 | | * OTOH, if wr isn't part of CT, we should invoke the callback: the |
874 | | * weakref outlived the trash. Note that since wr isn't CT in this |
875 | | * case, its callback can't be CT either -- wr acted as an external |
876 | | * root to this generation, and therefore its callback did too. So |
877 | | * nothing in CT is reachable from the callback either, so it's hard |
878 | | * to imagine how calling it later could create a problem for us. wr |
879 | | * is moved to wrcb_to_call in this case. |
880 | | */ |
881 | 20.7k | if (gc_is_collecting(AS_GC((PyObject *)wr))) { |
882 | 0 | continue; |
883 | 0 | } |
884 | | |
885 | | /* Create a new reference so that wr can't go away |
886 | | * before we can process it again. |
887 | | */ |
888 | 20.7k | Py_INCREF(wr); |
889 | | |
890 | | /* Move wr to wrcb_to_call, for the next pass. */ |
891 | 20.7k | PyGC_Head *wrasgc = AS_GC((PyObject *)wr); |
892 | | // wrasgc is reachable, but next isn't, so they can't be the same |
893 | 20.7k | _PyObject_ASSERT((PyObject *)wr, wrasgc != next); |
894 | 20.7k | gc_list_move(wrasgc, &wrcb_to_call); |
895 | 20.7k | } |
896 | 1.84M | } |
897 | | |
898 | | /* Invoke the callbacks we decided to honor. It's safe to invoke them |
899 | | * because they can't reference unreachable objects. |
900 | | */ |
901 | 109k | if (!*needs_resurrection_check) { |
902 | 109k | *needs_resurrection_check = !gc_list_is_empty(&wrcb_to_call); |
903 | 109k | } |
904 | 130k | while (! gc_list_is_empty(&wrcb_to_call)) { |
905 | 20.7k | PyObject *temp; |
906 | 20.7k | PyObject *callback; |
907 | | |
908 | 20.7k | gc = (PyGC_Head*)wrcb_to_call._gc_next; |
909 | 20.7k | PyObject *op = FROM_GC(gc); |
910 | 20.7k | _PyObject_ASSERT(op, PyWeakref_Check(op)); |
911 | 20.7k | PyWeakReference *wr = (PyWeakReference *)op; |
912 | 20.7k | callback = wr->wr_callback; |
913 | 20.7k | _PyObject_ASSERT(op, callback != NULL); |
914 | | |
915 | | /* copy-paste of weakrefobject.c's handle_callback() */ |
916 | 20.7k | temp = PyObject_CallOneArg(callback, (PyObject *)wr); |
917 | 20.7k | if (temp == NULL) { |
918 | 0 | PyErr_FormatUnraisable("Exception ignored on " |
919 | 0 | "calling weakref callback %R", callback); |
920 | 0 | } |
921 | 20.7k | else { |
922 | 20.7k | Py_DECREF(temp); |
923 | 20.7k | } |
924 | | |
925 | | /* Give up the reference we created in the first pass. When |
926 | | * op's refcount hits 0 (which it may or may not do right now), |
927 | | * op's tp_dealloc will decref op->wr_callback too. Note |
928 | | * that the refcount probably will hit 0 now, and because this |
929 | | * weakref was reachable to begin with, gc didn't already |
930 | | * add it to its count of freed objects. Example: a reachable |
931 | | * weak value dict maps some key to this reachable weakref. |
932 | | * The callback removes this key->weakref mapping from the |
933 | | * dict, leaving no other references to the weakref (excepting |
934 | | * ours). |
935 | | */ |
936 | 20.7k | Py_DECREF(op); |
937 | 20.7k | if (wrcb_to_call._gc_next == (uintptr_t)gc) { |
938 | | /* object is still alive -- move it */ |
939 | 0 | gc_list_move(gc, old); |
940 | 0 | } |
941 | 20.7k | else { |
942 | 20.7k | ++num_freed; |
943 | 20.7k | } |
944 | 20.7k | } |
945 | | |
946 | 109k | return num_freed; |
947 | 109k | } |
948 | | |
949 | | /* Clear all weakrefs to unreachable objects. When this returns, no object in |
950 | | * `unreachable` is weakly referenced anymore. See the comments above |
951 | | * handle_weakref_callbacks() for why these weakrefs need to be cleared. |
952 | | */ |
953 | | static void |
954 | | clear_weakrefs(PyGC_Head *unreachable) |
955 | 109k | { |
956 | 109k | PyGC_Head *gc; |
957 | 109k | PyGC_Head *next; |
958 | | |
959 | 6.79M | for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) { |
960 | 6.68M | PyWeakReference **wrlist; |
961 | | |
962 | 6.68M | PyObject *op = FROM_GC(gc); |
963 | 6.68M | next = GC_NEXT(gc); |
964 | | |
965 | 6.68M | if (PyWeakref_Check(op)) { |
966 | | /* A weakref inside the unreachable set is always cleared. See |
967 | | * the comments above handle_weakref_callbacks() for why these |
968 | | * must be cleared. |
969 | | */ |
970 | 8 | _PyWeakref_ClearRef((PyWeakReference *)op); |
971 | 8 | } |
972 | | |
973 | 6.68M | if (! _PyType_SUPPORTS_WEAKREFS(Py_TYPE(op))) { |
974 | 4.83M | continue; |
975 | 4.83M | } |
976 | | |
977 | | /* It supports weakrefs. Does it have any? |
978 | | * |
979 | | * This is never triggered for static types so we can avoid the |
980 | | * (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR(). |
981 | | */ |
982 | 1.84M | wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op); |
983 | | |
984 | | /* `op` may have some weakrefs. March over the list, clear |
985 | | * all the weakrefs. |
986 | | */ |
987 | 2.06M | for (PyWeakReference *wr = *wrlist; wr != NULL; wr = *wrlist) { |
988 | | /* _PyWeakref_ClearRef clears the weakref but leaves |
989 | | * the callback pointer intact. Obscure: it also |
990 | | * changes *wrlist. |
991 | | */ |
992 | 212k | _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op); |
993 | 212k | _PyWeakref_ClearRef(wr); |
994 | 212k | _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None); |
995 | 212k | } |
996 | 1.84M | } |
997 | 109k | } |
998 | | |
999 | | static void |
1000 | | debug_cycle(const char *msg, PyObject *op) |
1001 | 0 | { |
1002 | 0 | PySys_FormatStderr("gc: %s <%s %p>\n", |
1003 | 0 | msg, Py_TYPE(op)->tp_name, op); |
1004 | 0 | } |
1005 | | |
1006 | | /* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable |
1007 | | * only from such cycles). |
1008 | | * If _PyGC_DEBUG_SAVEALL, all objects in finalizers are appended to the module |
1009 | | * garbage list (a Python list), else only the objects in finalizers with |
1010 | | * __del__ methods are appended to garbage. All objects in finalizers are |
1011 | | * merged into the old list regardless. |
1012 | | */ |
1013 | | static void |
1014 | | handle_legacy_finalizers(PyThreadState *tstate, |
1015 | | GCState *gcstate, |
1016 | | PyGC_Head *finalizers, PyGC_Head *old) |
1017 | 109k | { |
1018 | 109k | assert(!_PyErr_Occurred(tstate)); |
1019 | 109k | assert(gcstate->garbage != NULL); |
1020 | | |
1021 | 109k | PyGC_Head *gc = GC_NEXT(finalizers); |
1022 | 109k | for (; gc != finalizers; gc = GC_NEXT(gc)) { |
1023 | 0 | PyObject *op = FROM_GC(gc); |
1024 | |
|
1025 | 0 | if ((gcstate->debug & _PyGC_DEBUG_SAVEALL) || has_legacy_finalizer(op)) { |
1026 | 0 | if (PyList_Append(gcstate->garbage, op) < 0) { |
1027 | 0 | _PyErr_Clear(tstate); |
1028 | 0 | break; |
1029 | 0 | } |
1030 | 0 | } |
1031 | 0 | } |
1032 | | |
1033 | 109k | gc_list_merge(finalizers, old); |
1034 | 109k | } |
1035 | | |
1036 | | /* Run first-time finalizers (if any) on all the objects in collectable. |
1037 | | * Note that this may remove some (or even all) of the objects from the |
1038 | | * list, due to refcounts falling to 0. |
1039 | | */ |
1040 | | static void |
1041 | | finalize_garbage(PyThreadState *tstate, PyGC_Head *collectable, |
1042 | | bool *needs_resurrection_check) |
1043 | 109k | { |
1044 | 109k | destructor finalize; |
1045 | 109k | PyGC_Head seen; |
1046 | | |
1047 | | /* While we're going through the loop, `finalize(op)` may cause op, or |
1048 | | * other objects, to be reclaimed via refcounts falling to zero. So |
1049 | | * there's little we can rely on about the structure of the input |
1050 | | * `collectable` list across iterations. For safety, we always take the |
1051 | | * first object in that list and move it to a temporary `seen` list. |
1052 | | * If objects vanish from the `collectable` and `seen` lists we don't |
1053 | | * care. |
1054 | | */ |
1055 | 109k | gc_list_init(&seen); |
1056 | | |
1057 | 6.79M | while (!gc_list_is_empty(collectable)) { |
1058 | 6.68M | PyGC_Head *gc = GC_NEXT(collectable); |
1059 | 6.68M | PyObject *op = FROM_GC(gc); |
1060 | 6.68M | gc_list_move(gc, &seen); |
1061 | 6.68M | if (!_PyGC_FINALIZED(op) && |
1062 | 6.68M | (finalize = Py_TYPE(op)->tp_finalize) != NULL) |
1063 | 2 | { |
1064 | 2 | if (!_PyGen_FinalizerIsNoop(op)) { |
1065 | 2 | *needs_resurrection_check = true; |
1066 | 2 | } |
1067 | 2 | _PyGC_SET_FINALIZED(op); |
1068 | 2 | Py_INCREF(op); |
1069 | 2 | finalize(op); |
1070 | 2 | assert(!_PyErr_Occurred(tstate)); |
1071 | 2 | Py_DECREF(op); |
1072 | 2 | } |
1073 | 6.68M | } |
1074 | 109k | gc_list_merge(&seen, collectable); |
1075 | 109k | } |
1076 | | |
1077 | | /* Break reference cycles by clearing the containers involved. This is |
1078 | | * tricky business as the lists can be changing and we don't know which |
1079 | | * objects may be freed. It is possible I screwed something up here. |
1080 | | */ |
1081 | | static void |
1082 | | delete_garbage(PyThreadState *tstate, GCState *gcstate, |
1083 | | PyGC_Head *collectable, PyGC_Head *old) |
1084 | 109k | { |
1085 | 109k | assert(!_PyErr_Occurred(tstate)); |
1086 | | |
1087 | 2.75M | while (!gc_list_is_empty(collectable)) { |
1088 | 2.64M | PyGC_Head *gc = GC_NEXT(collectable); |
1089 | 2.64M | PyObject *op = FROM_GC(gc); |
1090 | | |
1091 | 2.64M | _PyObject_ASSERT_WITH_MSG(op, Py_REFCNT(op) > 0, |
1092 | 2.64M | "refcount is too small"); |
1093 | | |
1094 | 2.64M | if (gcstate->debug & _PyGC_DEBUG_SAVEALL) { |
1095 | 0 | assert(gcstate->garbage != NULL); |
1096 | 0 | if (PyList_Append(gcstate->garbage, op) < 0) { |
1097 | 0 | _PyErr_Clear(tstate); |
1098 | 0 | } |
1099 | 0 | } |
1100 | 2.64M | else { |
1101 | 2.64M | inquiry clear; |
1102 | 2.64M | if ((clear = Py_TYPE(op)->tp_clear) != NULL) { |
1103 | 2.36M | Py_INCREF(op); |
1104 | 2.36M | (void) clear(op); |
1105 | 2.36M | if (_PyErr_Occurred(tstate)) { |
1106 | 0 | PyErr_FormatUnraisable("Exception ignored in tp_clear of %s", |
1107 | 0 | Py_TYPE(op)->tp_name); |
1108 | 0 | } |
1109 | 2.36M | Py_DECREF(op); |
1110 | 2.36M | } |
1111 | 2.64M | } |
1112 | 2.64M | if (GC_NEXT(collectable) == gc) { |
1113 | | /* object is still alive, move it, it may die later */ |
1114 | 2.15M | gc_clear_collecting(gc); |
1115 | 2.15M | gc_list_move(gc, old); |
1116 | 2.15M | } |
1117 | 2.64M | } |
1118 | 109k | } |
1119 | | |
1120 | | |
1121 | | // Show stats for objects in each generations |
1122 | | static void |
1123 | | show_stats_each_generations(GCState *gcstate) |
1124 | 0 | { |
1125 | 0 | char buf[100]; |
1126 | 0 | size_t pos = 0; |
1127 | |
|
1128 | 0 | for (int i = 0; i < NUM_GENERATIONS && pos < sizeof(buf); i++) { |
1129 | 0 | pos += PyOS_snprintf(buf+pos, sizeof(buf)-pos, |
1130 | 0 | " %zd", |
1131 | 0 | gc_list_size(GEN_HEAD(gcstate, i))); |
1132 | 0 | } |
1133 | |
|
1134 | 0 | PySys_FormatStderr( |
1135 | 0 | "gc: objects in each generation:%s\n" |
1136 | 0 | "gc: objects in permanent generation: %zd\n", |
1137 | 0 | buf, gc_list_size(&gcstate->permanent_generation.head)); |
1138 | 0 | } |
1139 | | |
1140 | | /* Deduce which objects among "base" are unreachable from outside the list |
1141 | | and move them to 'unreachable'. The process consist in the following steps: |
1142 | | |
1143 | | 1. Copy all reference counts to a different field (gc_prev is used to hold |
1144 | | this copy to save memory). |
1145 | | 2. Traverse all objects in "base" and visit all referred objects using |
1146 | | "tp_traverse" and for every visited object, subtract 1 to the reference |
1147 | | count (the one that we copied in the previous step). After this step, all |
1148 | | objects that can be reached directly from outside must have strictly positive |
1149 | | reference count, while all unreachable objects must have a count of exactly 0. |
1150 | | 3. Identify all unreachable objects (the ones with 0 reference count) and move |
1151 | | them to the "unreachable" list. This step also needs to move back to "base" all |
1152 | | objects that were initially marked as unreachable but are referred transitively |
1153 | | by the reachable objects (the ones with strictly positive reference count). |
1154 | | |
1155 | | Contracts: |
1156 | | |
1157 | | * The "base" has to be a valid list with no mask set. |
1158 | | |
1159 | | * The "unreachable" list must be uninitialized (this function calls |
1160 | | gc_list_init over 'unreachable'). |
1161 | | |
1162 | | IMPORTANT: This function leaves 'unreachable' with the NEXT_MASK_UNREACHABLE |
1163 | | flag set but it does not clear it to skip unnecessary iteration. Before the |
1164 | | flag is cleared (for example, by using 'clear_unreachable_mask' function or |
1165 | | by a call to 'move_legacy_finalizers'), the 'unreachable' list is not a normal |
1166 | | list and we can not use most gc_list_* functions for it. */ |
1167 | | static inline Py_ssize_t |
1168 | | deduce_unreachable(PyGC_Head *base, PyGC_Head *unreachable, |
1169 | 111k | Py_ssize_t *reachable) { |
1170 | 111k | validate_list(base, collecting_clear_unreachable_clear); |
1171 | | /* Using ob_refcnt and gc_refs, calculate which objects in the |
1172 | | * container set are reachable from outside the set (i.e., have a |
1173 | | * refcount greater than 0 when all the references within the |
1174 | | * set are taken into account). |
1175 | | */ |
1176 | 111k | Py_ssize_t candidates = update_refs(base); // gc_prev is used for gc_refs |
1177 | 111k | subtract_refs(base); |
1178 | | |
1179 | | /* Leave everything reachable from outside base in base, and move |
1180 | | * everything else (in base) to unreachable. |
1181 | | * |
1182 | | * NOTE: This used to move the reachable objects into a reachable |
1183 | | * set instead. But most things usually turn out to be reachable, |
1184 | | * so it's more efficient to move the unreachable things. It "sounds slick" |
1185 | | * to move the unreachable objects, until you think about it - the reason it |
1186 | | * pays isn't actually obvious. |
1187 | | * |
1188 | | * Suppose we create objects A, B, C in that order. They appear in the young |
1189 | | * generation in the same order. If B points to A, and C to B, and C is |
1190 | | * reachable from outside, then the adjusted refcounts will be 0, 0, and 1 |
1191 | | * respectively. |
1192 | | * |
1193 | | * When move_unreachable finds A, A is moved to the unreachable list. The |
1194 | | * same for B when it's first encountered. Then C is traversed, B is moved |
1195 | | * _back_ to the reachable list. B is eventually traversed, and then A is |
1196 | | * moved back to the reachable list. |
1197 | | * |
1198 | | * So instead of not moving at all, the reachable objects B and A are moved |
1199 | | * twice each. Why is this a win? A straightforward algorithm to move the |
1200 | | * reachable objects instead would move A, B, and C once each. |
1201 | | * |
1202 | | * The key is that this dance leaves the objects in order C, B, A - it's |
1203 | | * reversed from the original order. On all _subsequent_ scans, none of |
1204 | | * them will move. Since most objects aren't in cycles, this can save an |
1205 | | * unbounded number of moves across an unbounded number of later collections. |
1206 | | * It can cost more only the first time the chain is scanned. |
1207 | | * |
1208 | | * Drawback: move_unreachable is also used to find out what's still trash |
1209 | | * after finalizers may resurrect objects. In _that_ case most unreachable |
1210 | | * objects will remain unreachable, so it would be more efficient to move |
1211 | | * the reachable objects instead. But this is a one-time cost, probably not |
1212 | | * worth complicating the code to speed just a little. |
1213 | | */ |
1214 | 111k | gc_list_init(unreachable); |
1215 | | // gc_prev is pointer again |
1216 | 111k | *reachable = move_unreachable(base, unreachable); |
1217 | 111k | validate_list(base, collecting_clear_unreachable_clear); |
1218 | 111k | validate_list(unreachable, collecting_set_unreachable_set); |
1219 | 111k | return candidates; |
1220 | 111k | } |
1221 | | |
1222 | | /* Handle objects that may have resurrected after a call to 'finalize_garbage', moving |
1223 | | them to 'old_generation' and placing the rest on 'still_unreachable'. |
1224 | | |
1225 | | Contracts: |
1226 | | * After this function 'unreachable' must not be used anymore and 'still_unreachable' |
1227 | | will contain the objects that did not resurrect. |
1228 | | |
1229 | | * The "still_unreachable" list must be uninitialized (this function calls |
1230 | | gc_list_init over 'still_unreachable'). |
1231 | | |
1232 | | IMPORTANT: After a call to this function, the 'still_unreachable' set will have the |
1233 | | PREV_MARK_COLLECTING set, but the objects in this set are going to be removed so |
1234 | | we can skip the expense of clearing the flag to avoid extra iteration. */ |
1235 | | static inline void |
1236 | | handle_resurrected_objects(PyGC_Head *unreachable, PyGC_Head* still_unreachable, |
1237 | | PyGC_Head *old_generation) |
1238 | 1.70k | { |
1239 | | // Remove the PREV_MASK_COLLECTING from unreachable |
1240 | | // to prepare it for a new call to 'deduce_unreachable' |
1241 | 1.70k | gc_list_clear_collecting(unreachable); |
1242 | | |
1243 | | // After the call to deduce_unreachable, the 'still_unreachable' set will |
1244 | | // have the PREV_MARK_COLLECTING set, but the objects are going to be |
1245 | | // removed so we can skip the expense of clearing the flag. |
1246 | 1.70k | PyGC_Head* resurrected = unreachable; |
1247 | 1.70k | Py_ssize_t reachable; |
1248 | 1.70k | deduce_unreachable(resurrected, still_unreachable, &reachable); |
1249 | 1.70k | clear_unreachable_mask(still_unreachable); |
1250 | | |
1251 | | // Move the resurrected objects to the old generation for future collection. |
1252 | 1.70k | gc_list_merge(resurrected, old_generation); |
1253 | 1.70k | } |
1254 | | |
1255 | | |
1256 | | /* Invoke progress callbacks to notify clients that garbage collection |
1257 | | * is starting or stopping |
1258 | | */ |
1259 | | static void |
1260 | | invoke_gc_callback(PyThreadState *tstate, const char *phase, |
1261 | | int generation, struct gc_generation_stats *stats) |
1262 | 219k | { |
1263 | 219k | assert(!_PyErr_Occurred(tstate)); |
1264 | | |
1265 | | /* we may get called very early */ |
1266 | 219k | GCState *gcstate = &tstate->interp->gc; |
1267 | 219k | if (gcstate->callbacks == NULL) { |
1268 | 0 | return; |
1269 | 0 | } |
1270 | | |
1271 | | /* The local variable cannot be rebound, check it for sanity */ |
1272 | 219k | assert(PyList_CheckExact(gcstate->callbacks)); |
1273 | 219k | PyObject *info = NULL; |
1274 | 219k | if (PyList_GET_SIZE(gcstate->callbacks) != 0) { |
1275 | 3.41k | info = Py_BuildValue("{sisnsnsnsd}", |
1276 | 3.41k | "generation", generation, |
1277 | 3.41k | "collected", stats->collected, |
1278 | 3.41k | "uncollectable", stats->uncollectable, |
1279 | 3.41k | "candidates", stats->candidates, |
1280 | 3.41k | "duration", stats->duration); |
1281 | 3.41k | if (info == NULL) { |
1282 | 0 | PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks"); |
1283 | 0 | return; |
1284 | 0 | } |
1285 | 3.41k | } |
1286 | | |
1287 | 219k | PyObject *phase_obj = PyUnicode_FromString(phase); |
1288 | 219k | if (phase_obj == NULL) { |
1289 | 0 | Py_XDECREF(info); |
1290 | 0 | PyErr_FormatUnraisable("Exception ignored on invoking gc callbacks"); |
1291 | 0 | return; |
1292 | 0 | } |
1293 | | |
1294 | 219k | PyObject *stack[] = {phase_obj, info}; |
1295 | 222k | for (Py_ssize_t i=0; i<PyList_GET_SIZE(gcstate->callbacks); i++) { |
1296 | 3.41k | PyObject *r, *cb = PyList_GET_ITEM(gcstate->callbacks, i); |
1297 | 3.41k | Py_INCREF(cb); /* make sure cb doesn't go away */ |
1298 | 3.41k | r = PyObject_Vectorcall(cb, stack, 2, NULL); |
1299 | 3.41k | if (r == NULL) { |
1300 | 0 | PyErr_FormatUnraisable("Exception ignored while " |
1301 | 0 | "calling GC callback %R", cb); |
1302 | 0 | } |
1303 | 3.41k | else { |
1304 | 3.41k | Py_DECREF(r); |
1305 | 3.41k | } |
1306 | 3.41k | Py_DECREF(cb); |
1307 | 3.41k | } |
1308 | 219k | Py_DECREF(phase_obj); |
1309 | 219k | Py_XDECREF(info); |
1310 | 219k | assert(!_PyErr_Occurred(tstate)); |
1311 | 219k | } |
1312 | | |
1313 | | |
1314 | | /* Find the oldest generation (highest numbered) where the count |
1315 | | * exceeds the threshold. Objects in the that generation and |
1316 | | * generations younger than it will be collected. */ |
1317 | | static int |
1318 | | gc_select_generation(GCState *gcstate) |
1319 | 127k | { |
1320 | 391k | for (int i = NUM_GENERATIONS-1; i >= 0; i--) { |
1321 | 372k | if (gcstate->generations[i].count > gcstate->generations[i].threshold) { |
1322 | | /* Avoid quadratic performance degradation in number |
1323 | | of tracked objects (see also issue #4074): |
1324 | | |
1325 | | To limit the cost of garbage collection, there are two strategies; |
1326 | | - make each collection faster, e.g. by scanning fewer objects |
1327 | | - do less collections |
1328 | | This heuristic is about the latter strategy. |
1329 | | |
1330 | | In addition to the various configurable thresholds, we only trigger a |
1331 | | full collection if the ratio |
1332 | | |
1333 | | long_lived_pending / long_lived_total |
1334 | | |
1335 | | is above a given value (hardwired to 25%). |
1336 | | |
1337 | | The reason is that, while "non-full" collections (i.e., collections of |
1338 | | the young and middle generations) will always examine roughly the same |
1339 | | number of objects -- determined by the aforementioned thresholds --, |
1340 | | the cost of a full collection is proportional to the total number of |
1341 | | long-lived objects, which is virtually unbounded. |
1342 | | |
1343 | | Indeed, it has been remarked that doing a full collection every |
1344 | | <constant number> of object creations entails a dramatic performance |
1345 | | degradation in workloads which consist in creating and storing lots of |
1346 | | long-lived objects (e.g. building a large list of GC-tracked objects would |
1347 | | show quadratic performance, instead of linear as expected: see issue #4074). |
1348 | | |
1349 | | Using the above ratio, instead, yields amortized linear performance in |
1350 | | the total number of objects (the effect of which can be summarized |
1351 | | thusly: "each full garbage collection is more and more costly as the |
1352 | | number of objects grows, but we do fewer and fewer of them"). |
1353 | | |
1354 | | This heuristic was suggested by Martin von Löwis on python-dev in |
1355 | | June 2008. His original analysis and proposal can be found at: |
1356 | | http://mail.python.org/pipermail/python-dev/2008-June/080579.html |
1357 | | */ |
1358 | 118k | if (i == NUM_GENERATIONS - 1 |
1359 | 9.27k | && gcstate->long_lived_pending < gcstate->long_lived_total / 4) |
1360 | 8.51k | { |
1361 | 8.51k | continue; |
1362 | 8.51k | } |
1363 | 109k | return i; |
1364 | 118k | } |
1365 | 372k | } |
1366 | 18.2k | return -1; |
1367 | 127k | } |
1368 | | |
1369 | | static struct gc_generation_stats * |
1370 | | gc_get_stats(GCState *gcstate, int gen) |
1371 | 109k | { |
1372 | 109k | if (gen == 0) { |
1373 | 99.7k | struct gc_young_stats_buffer *buffer = &gcstate->generation_stats->young; |
1374 | 99.7k | buffer->index = (buffer->index + 1) % GC_YOUNG_STATS_SIZE; |
1375 | 99.7k | struct gc_generation_stats *stats = &buffer->items[buffer->index]; |
1376 | 99.7k | return stats; |
1377 | 99.7k | } |
1378 | 9.80k | else { |
1379 | 9.80k | struct gc_old_stats_buffer *buffer = &gcstate->generation_stats->old[gen - 1]; |
1380 | 9.80k | buffer->index = (buffer->index + 1) % GC_OLD_STATS_SIZE; |
1381 | 9.80k | struct gc_generation_stats *stats = &buffer->items[buffer->index]; |
1382 | 9.80k | return stats; |
1383 | 9.80k | } |
1384 | 109k | } |
1385 | | |
1386 | | static struct gc_generation_stats * |
1387 | | gc_get_prev_stats(GCState *gcstate, int gen) |
1388 | 109k | { |
1389 | 109k | if (gen == 0) { |
1390 | 99.7k | struct gc_young_stats_buffer *buffer = &gcstate->generation_stats->young; |
1391 | 99.7k | struct gc_generation_stats *stats = &buffer->items[buffer->index]; |
1392 | 99.7k | return stats; |
1393 | 99.7k | } |
1394 | 9.80k | else { |
1395 | 9.80k | struct gc_old_stats_buffer *buffer = &gcstate->generation_stats->old[gen - 1]; |
1396 | 9.80k | struct gc_generation_stats *stats = &buffer->items[buffer->index]; |
1397 | 9.80k | return stats; |
1398 | 9.80k | } |
1399 | 109k | } |
1400 | | |
1401 | | static void |
1402 | | add_stats(GCState *gcstate, int gen, struct gc_generation_stats *stats) |
1403 | 109k | { |
1404 | 109k | struct gc_stats *generation_stats = gcstate->generation_stats; |
1405 | 109k | uint32_t seq = _Py_atomic_load_uint32_relaxed(&generation_stats->update_seq); |
1406 | 109k | assert((seq & 1) == 0); |
1407 | | /* Odd seq tells the reader that an update is in progress. */ |
1408 | 109k | _Py_atomic_store_uint32_relaxed(&generation_stats->update_seq, seq + 1); |
1409 | 109k | _Py_atomic_fence_seq_cst(); |
1410 | | |
1411 | 109k | struct gc_generation_stats *prev_stats = gc_get_prev_stats(gcstate, gen); |
1412 | 109k | struct gc_generation_stats *cur_stats = gc_get_stats(gcstate, gen); |
1413 | | |
1414 | 109k | memcpy(cur_stats, prev_stats, sizeof(struct gc_generation_stats)); |
1415 | | |
1416 | 109k | cur_stats->ts_start = stats->ts_start; |
1417 | 109k | cur_stats->collections += 1; |
1418 | 109k | cur_stats->collected += stats->collected; |
1419 | 109k | cur_stats->uncollectable += stats->uncollectable; |
1420 | 109k | cur_stats->candidates += stats->candidates; |
1421 | | |
1422 | 109k | cur_stats->duration += stats->duration; |
1423 | 109k | cur_stats->heap_size = stats->heap_size; |
1424 | 109k | cur_stats->ts_stop = stats->ts_stop; |
1425 | 109k | _Py_atomic_store_uint32_release(&generation_stats->update_seq, seq + 2); |
1426 | 109k | } |
1427 | | |
1428 | | /* This is the main function. Read this to understand how the |
1429 | | * collection process works. */ |
1430 | | static Py_ssize_t |
1431 | | gc_collect_main(PyThreadState *tstate, int generation, _PyGC_Reason reason) |
1432 | 127k | { |
1433 | 127k | int i; |
1434 | 127k | PyGC_Head *young; /* the generation we are examining */ |
1435 | 127k | PyGC_Head *old; /* next older generation */ |
1436 | 127k | PyGC_Head unreachable; /* non-problematic unreachable trash */ |
1437 | 127k | PyGC_Head finalizers; /* objects with, & reachable from, __del__ */ |
1438 | 127k | PyGC_Head *gc; |
1439 | 127k | GCState *gcstate = &tstate->interp->gc; |
1440 | | |
1441 | | // gc_collect_main() must not be called before _PyGC_Init |
1442 | | // or after _PyGC_Fini() |
1443 | 127k | assert(gcstate->garbage != NULL); |
1444 | 127k | assert(!_PyErr_Occurred(tstate)); |
1445 | | |
1446 | 127k | int expected = 0; |
1447 | 127k | if (!_Py_atomic_compare_exchange_int(&gcstate->collecting, &expected, 1)) { |
1448 | | // Don't start a garbage collection if one is already in progress. |
1449 | 0 | return 0; |
1450 | 0 | } |
1451 | 127k | gcstate->frame = tstate->current_frame; |
1452 | | |
1453 | 127k | if (generation == GENERATION_AUTO) { |
1454 | | // Select the oldest generation that needs collecting. We will collect |
1455 | | // objects from that generation and all generations younger than it. |
1456 | 127k | generation = gc_select_generation(gcstate); |
1457 | 127k | if (generation < 0) { |
1458 | | // No generation needs to be collected. |
1459 | 18.2k | _Py_atomic_store_int(&gcstate->collecting, 0); |
1460 | 18.2k | return 0; |
1461 | 18.2k | } |
1462 | 127k | } |
1463 | | |
1464 | 127k | assert(generation >= 0 && generation < NUM_GENERATIONS); |
1465 | | |
1466 | | #ifdef Py_STATS |
1467 | | { |
1468 | | PyStats *s = _PyStats_GET(); |
1469 | | if (s) { |
1470 | | s->object_stats.object_visits = 0; |
1471 | | } |
1472 | | } |
1473 | | #endif |
1474 | | |
1475 | 109k | GC_STAT_ADD(generation, collections, 1); |
1476 | | |
1477 | 109k | struct gc_generation_stats stats = { 0 }; |
1478 | 109k | if (reason != _Py_GC_REASON_SHUTDOWN) { |
1479 | 109k | invoke_gc_callback(tstate, "start", generation, &stats); |
1480 | 109k | } |
1481 | | |
1482 | 109k | stats.heap_size = gcstate->heap_size; |
1483 | | // ignore error: don't interrupt the GC if reading the clock fails |
1484 | 109k | (void)PyTime_PerfCounterRaw(&stats.ts_start); |
1485 | 109k | if (gcstate->debug & _PyGC_DEBUG_STATS) { |
1486 | 0 | PySys_WriteStderr("gc: collecting generation %d...\n", generation); |
1487 | 0 | show_stats_each_generations(gcstate); |
1488 | 0 | } |
1489 | | |
1490 | 109k | if (PyDTrace_GC_START_ENABLED()) { |
1491 | 0 | PyDTrace_GC_START(generation); |
1492 | 0 | } |
1493 | | |
1494 | | /* update collection and allocation counters */ |
1495 | 109k | if (generation+1 < NUM_GENERATIONS) { |
1496 | 108k | gcstate->generations[generation+1].count += 1; |
1497 | 108k | } |
1498 | 229k | for (i = 0; i <= generation; i++) { |
1499 | 120k | gcstate->generations[i].count = 0; |
1500 | 120k | } |
1501 | | |
1502 | | /* merge younger generations with one we are currently collecting */ |
1503 | 120k | for (i = 0; i < generation; i++) { |
1504 | 10.5k | gc_list_merge(GEN_HEAD(gcstate, i), GEN_HEAD(gcstate, generation)); |
1505 | 10.5k | } |
1506 | | |
1507 | | /* handy references */ |
1508 | 109k | young = GEN_HEAD(gcstate, generation); |
1509 | 109k | if (generation < NUM_GENERATIONS-1) { |
1510 | 108k | old = GEN_HEAD(gcstate, generation+1); |
1511 | 108k | } |
1512 | 754 | else { |
1513 | 754 | old = young; |
1514 | 754 | } |
1515 | 109k | validate_list(old, collecting_clear_unreachable_clear); |
1516 | | |
1517 | 109k | Py_ssize_t reachable; |
1518 | 109k | stats.candidates = deduce_unreachable(young, &unreachable, &reachable); |
1519 | | |
1520 | | /* Move reachable objects to next generation. */ |
1521 | 109k | if (young != old) { |
1522 | 108k | if (generation == NUM_GENERATIONS - 2) { |
1523 | 9.05k | gcstate->long_lived_pending += reachable; |
1524 | 9.05k | } |
1525 | 108k | gc_list_merge(young, old); |
1526 | 108k | } |
1527 | 754 | else { |
1528 | | // In Python <= 3.13, we called untrack_dicts(young) here to untrack |
1529 | | // atomic-only dicts (see issue #14775). Python 3.14 removed the lazy |
1530 | | // dict tracking machinery entirely (GH-127010) -- dicts are always |
1531 | | // tracked from creation and never untracked by GC. That way, we don't |
1532 | | // have to restore MAINTAIN_TRACKING across every PyDict_SetItem call |
1533 | | // site; the cost is slightly more work for full collections on dicts |
1534 | | // with only atomic values. |
1535 | 754 | gcstate->long_lived_pending = 0; |
1536 | 754 | gcstate->long_lived_total = reachable; |
1537 | 754 | } |
1538 | | |
1539 | | /* All objects in unreachable are trash, but objects reachable from |
1540 | | * legacy finalizers (e.g. tp_del) can't safely be deleted. |
1541 | | */ |
1542 | 109k | gc_list_init(&finalizers); |
1543 | | // NEXT_MASK_UNREACHABLE is cleared here. |
1544 | | // After move_legacy_finalizers(), unreachable is normal list. |
1545 | 109k | move_legacy_finalizers(&unreachable, &finalizers); |
1546 | | /* finalizers contains the unreachable objects with a legacy finalizer; |
1547 | | * unreachable objects reachable *from* those are also uncollectable, |
1548 | | * and we move those into the finalizers list too. |
1549 | | */ |
1550 | 109k | move_legacy_finalizer_reachable(&finalizers); |
1551 | | |
1552 | 109k | validate_list(&finalizers, collecting_clear_unreachable_clear); |
1553 | 109k | validate_list(&unreachable, collecting_set_unreachable_clear); |
1554 | | |
1555 | 109k | bool needs_resurrection_check = false; |
1556 | | |
1557 | | /* Print debugging information. */ |
1558 | 109k | if (gcstate->debug & _PyGC_DEBUG_COLLECTABLE) { |
1559 | | /* sys.stderr.write() can resurrect objects. */ |
1560 | 0 | needs_resurrection_check = true; |
1561 | 0 | for (gc = GC_NEXT(&unreachable); gc != &unreachable; gc = GC_NEXT(gc)) { |
1562 | 0 | debug_cycle("collectable", FROM_GC(gc)); |
1563 | 0 | } |
1564 | 0 | } |
1565 | | |
1566 | | /* Clear weakrefs and invoke callbacks as necessary. */ |
1567 | 109k | stats.collected += handle_weakref_callbacks(&unreachable, old, |
1568 | 109k | &needs_resurrection_check); |
1569 | 109k | validate_list(old, collecting_clear_unreachable_clear); |
1570 | 109k | validate_list(&unreachable, collecting_set_unreachable_clear); |
1571 | | |
1572 | | /* Call tp_finalize on objects which have one. */ |
1573 | 109k | finalize_garbage(tstate, &unreachable, &needs_resurrection_check); |
1574 | | |
1575 | | /* Handle any objects that may have resurrected after the call |
1576 | | * to 'finalize_garbage' and continue the collection with the |
1577 | | * objects that are still unreachable */ |
1578 | 109k | PyGC_Head final_unreachable; |
1579 | 109k | if (needs_resurrection_check) { |
1580 | 1.70k | handle_resurrected_objects(&unreachable, &final_unreachable, old); |
1581 | 1.70k | } |
1582 | 107k | else { |
1583 | | /* No Python code ran during finalization, so the original |
1584 | | * unreachable set is still valid. */ |
1585 | 107k | gc_list_init(&final_unreachable); |
1586 | 107k | gc_list_merge(&unreachable, &final_unreachable); |
1587 | 107k | } |
1588 | | |
1589 | | /* Clear weakrefs to objects in the unreachable set. No Python-level |
1590 | | * code must be allowed to access those unreachable objects. During |
1591 | | * delete_garbage(), finalizers outside the unreachable set might run |
1592 | | * and create new weakrefs. If those weakrefs were not cleared, they |
1593 | | * could reveal unreachable objects. Callbacks are not executed. |
1594 | | */ |
1595 | 109k | clear_weakrefs(&final_unreachable); |
1596 | | |
1597 | | /* Call tp_clear on objects in the final_unreachable set. This will cause |
1598 | | * the reference cycles to be broken. It may also cause some objects |
1599 | | * in finalizers to be freed. |
1600 | | */ |
1601 | 109k | stats.collected += gc_list_size(&final_unreachable); |
1602 | 109k | delete_garbage(tstate, gcstate, &final_unreachable, old); |
1603 | | |
1604 | | /* Collect statistics on uncollectable objects found and print |
1605 | | * debugging information. */ |
1606 | 109k | Py_ssize_t n = 0; |
1607 | 109k | for (gc = GC_NEXT(&finalizers); gc != &finalizers; gc = GC_NEXT(gc)) { |
1608 | 0 | n++; |
1609 | 0 | if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) |
1610 | 0 | debug_cycle("uncollectable", FROM_GC(gc)); |
1611 | 0 | } |
1612 | 109k | stats.uncollectable = n; |
1613 | 109k | (void)PyTime_PerfCounterRaw(&stats.ts_stop); |
1614 | 109k | stats.duration = PyTime_AsSecondsDouble(stats.ts_stop - stats.ts_start); |
1615 | 109k | if (gcstate->debug & _PyGC_DEBUG_STATS) { |
1616 | 0 | PySys_WriteStderr( |
1617 | 0 | "gc: done, %zd unreachable, %zd uncollectable, %.4fs elapsed\n", |
1618 | 0 | stats.uncollectable+stats.collected, stats.uncollectable, |
1619 | 0 | stats.duration); |
1620 | 0 | } |
1621 | | |
1622 | | /* Append instances in the uncollectable set to a Python |
1623 | | * reachable list of garbage. The programmer has to deal with |
1624 | | * this if they insist on creating this type of structure. |
1625 | | */ |
1626 | 109k | handle_legacy_finalizers(tstate, gcstate, &finalizers, old); |
1627 | 109k | validate_list(old, collecting_clear_unreachable_clear); |
1628 | | |
1629 | | /* Clear free list only during the collection of the highest |
1630 | | * generation */ |
1631 | 109k | if (generation == NUM_GENERATIONS-1) { |
1632 | 754 | _PyGC_ClearAllFreeLists(tstate->interp); |
1633 | 754 | } |
1634 | | |
1635 | 109k | if (_PyErr_Occurred(tstate)) { |
1636 | 0 | if (reason == _Py_GC_REASON_SHUTDOWN) { |
1637 | 0 | _PyErr_Clear(tstate); |
1638 | 0 | } |
1639 | 0 | else { |
1640 | 0 | PyErr_FormatUnraisable("Exception ignored in garbage collection"); |
1641 | 0 | } |
1642 | 0 | } |
1643 | | |
1644 | | /* Update stats */ |
1645 | 109k | add_stats(gcstate, generation, &stats); |
1646 | 109k | GC_STAT_ADD(generation, objects_collected, stats.collected); |
1647 | | |
1648 | | #ifdef Py_STATS |
1649 | | { |
1650 | | PyStats *s = _PyStats_GET(); |
1651 | | if (s) { |
1652 | | GC_STAT_ADD(generation, object_visits, |
1653 | | s->object_stats.object_visits); |
1654 | | s->object_stats.object_visits = 0; |
1655 | | } |
1656 | | } |
1657 | | #endif |
1658 | | |
1659 | 109k | if (PyDTrace_GC_DONE_ENABLED()) { |
1660 | 0 | PyDTrace_GC_DONE(stats.uncollectable + stats.collected); |
1661 | 0 | } |
1662 | | |
1663 | 109k | if (reason != _Py_GC_REASON_SHUTDOWN) { |
1664 | 109k | invoke_gc_callback(tstate, "stop", generation, &stats); |
1665 | 109k | } |
1666 | | |
1667 | 109k | assert(!_PyErr_Occurred(tstate)); |
1668 | 109k | gcstate->frame = NULL; |
1669 | 109k | _Py_atomic_store_int(&gcstate->collecting, 0); |
1670 | 109k | return stats.uncollectable + stats.collected; |
1671 | 127k | } |
1672 | | |
1673 | | static int |
1674 | | referrersvisit(PyObject* obj, void *arg) |
1675 | 0 | { |
1676 | 0 | PyObject *objs = arg; |
1677 | 0 | Py_ssize_t i; |
1678 | 0 | for (i = 0; i < PyTuple_GET_SIZE(objs); i++) { |
1679 | 0 | if (PyTuple_GET_ITEM(objs, i) == obj) { |
1680 | 0 | return 1; |
1681 | 0 | } |
1682 | 0 | } |
1683 | 0 | return 0; |
1684 | 0 | } |
1685 | | |
1686 | | static int |
1687 | | gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist) |
1688 | 0 | { |
1689 | 0 | PyGC_Head *gc; |
1690 | 0 | PyObject *obj; |
1691 | 0 | traverseproc traverse; |
1692 | 0 | for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) { |
1693 | 0 | obj = FROM_GC(gc); |
1694 | 0 | traverse = Py_TYPE(obj)->tp_traverse; |
1695 | 0 | if (obj == objs || obj == resultlist) { |
1696 | 0 | continue; |
1697 | 0 | } |
1698 | 0 | if (traverse(obj, referrersvisit, objs)) { |
1699 | 0 | if (PyList_Append(resultlist, obj) < 0) { |
1700 | 0 | return 0; /* error */ |
1701 | 0 | } |
1702 | 0 | } |
1703 | 0 | } |
1704 | 0 | return 1; /* no error */ |
1705 | 0 | } |
1706 | | |
1707 | | PyObject * |
1708 | | _PyGC_GetReferrers(PyInterpreterState *interp, PyObject *objs) |
1709 | 0 | { |
1710 | 0 | PyObject *result = PyList_New(0); |
1711 | 0 | if (!result) { |
1712 | 0 | return NULL; |
1713 | 0 | } |
1714 | | |
1715 | 0 | GCState *gcstate = &interp->gc; |
1716 | 0 | for (int i = 0; i < NUM_GENERATIONS; i++) { |
1717 | 0 | if (!(gc_referrers_for(objs, GEN_HEAD(gcstate, i), result))) { |
1718 | 0 | Py_DECREF(result); |
1719 | 0 | return NULL; |
1720 | 0 | } |
1721 | 0 | } |
1722 | 0 | return result; |
1723 | 0 | } |
1724 | | |
1725 | | PyObject * |
1726 | | _PyGC_GetObjects(PyInterpreterState *interp, int generation) |
1727 | 0 | { |
1728 | 0 | assert(generation >= -1 && generation < NUM_GENERATIONS); |
1729 | 0 | GCState *gcstate = &interp->gc; |
1730 | |
|
1731 | 0 | PyObject *result = PyList_New(0); |
1732 | 0 | if (result == NULL) { |
1733 | 0 | return NULL; |
1734 | 0 | } |
1735 | | |
1736 | 0 | if (generation == -1) { |
1737 | | /* If generation is -1, get all objects from all generations */ |
1738 | 0 | for (int i = 0; i < NUM_GENERATIONS; i++) { |
1739 | 0 | if (append_objects(result, GEN_HEAD(gcstate, i))) { |
1740 | 0 | goto error; |
1741 | 0 | } |
1742 | 0 | } |
1743 | 0 | } |
1744 | 0 | else { |
1745 | 0 | if (append_objects(result, GEN_HEAD(gcstate, generation))) { |
1746 | 0 | goto error; |
1747 | 0 | } |
1748 | 0 | } |
1749 | | |
1750 | 0 | return result; |
1751 | 0 | error: |
1752 | 0 | Py_DECREF(result); |
1753 | 0 | return NULL; |
1754 | 0 | } |
1755 | | |
1756 | | void |
1757 | | _PyGC_Freeze(PyInterpreterState *interp) |
1758 | 0 | { |
1759 | 0 | GCState *gcstate = &interp->gc; |
1760 | 0 | for (int i = 0; i < NUM_GENERATIONS; ++i) { |
1761 | 0 | gc_list_merge(GEN_HEAD(gcstate, i), &gcstate->permanent_generation.head); |
1762 | 0 | gcstate->generations[i].count = 0; |
1763 | 0 | } |
1764 | 0 | } |
1765 | | |
1766 | | void |
1767 | | _PyGC_Unfreeze(PyInterpreterState *interp) |
1768 | 0 | { |
1769 | 0 | GCState *gcstate = &interp->gc; |
1770 | 0 | gc_list_merge(&gcstate->permanent_generation.head, |
1771 | 0 | GEN_HEAD(gcstate, NUM_GENERATIONS-1)); |
1772 | 0 | } |
1773 | | |
1774 | | Py_ssize_t |
1775 | | _PyGC_GetFreezeCount(PyInterpreterState *interp) |
1776 | 0 | { |
1777 | 0 | GCState *gcstate = &interp->gc; |
1778 | 0 | return gc_list_size(&gcstate->permanent_generation.head); |
1779 | 0 | } |
1780 | | |
1781 | | /* C API for controlling the state of the garbage collector */ |
1782 | | int |
1783 | | PyGC_Enable(void) |
1784 | 0 | { |
1785 | 0 | GCState *gcstate = get_gc_state(); |
1786 | 0 | int old_state = gcstate->enabled; |
1787 | 0 | gcstate->enabled = 1; |
1788 | 0 | return old_state; |
1789 | 0 | } |
1790 | | |
1791 | | int |
1792 | | PyGC_Disable(void) |
1793 | 0 | { |
1794 | 0 | GCState *gcstate = get_gc_state(); |
1795 | 0 | int old_state = gcstate->enabled; |
1796 | 0 | gcstate->enabled = 0; |
1797 | 0 | return old_state; |
1798 | 0 | } |
1799 | | |
1800 | | int |
1801 | | PyGC_IsEnabled(void) |
1802 | 0 | { |
1803 | 0 | GCState *gcstate = get_gc_state(); |
1804 | 0 | return gcstate->enabled; |
1805 | 0 | } |
1806 | | |
1807 | | /* Public API to invoke gc.collect() from C */ |
1808 | | Py_ssize_t |
1809 | | PyGC_Collect(void) |
1810 | 0 | { |
1811 | 0 | PyThreadState *tstate = _PyThreadState_GET(); |
1812 | 0 | GCState *gcstate = &tstate->interp->gc; |
1813 | |
|
1814 | 0 | if (!gcstate->enabled) { |
1815 | 0 | return 0; |
1816 | 0 | } |
1817 | | |
1818 | 0 | Py_ssize_t n; |
1819 | 0 | PyObject *exc = _PyErr_GetRaisedException(tstate); |
1820 | 0 | n = gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_MANUAL); |
1821 | 0 | _PyErr_SetRaisedException(tstate, exc); |
1822 | |
|
1823 | 0 | return n; |
1824 | 0 | } |
1825 | | |
1826 | | Py_ssize_t |
1827 | | _PyGC_Collect(PyThreadState *tstate, int generation, _PyGC_Reason reason) |
1828 | 0 | { |
1829 | 0 | return gc_collect_main(tstate, generation, reason); |
1830 | 0 | } |
1831 | | |
1832 | | void |
1833 | | _PyGC_CollectNoFail(PyThreadState *tstate) |
1834 | 0 | { |
1835 | | /* Ideally, this function is only called on interpreter shutdown, |
1836 | | and therefore not recursively. Unfortunately, when there are daemon |
1837 | | threads, a daemon thread can start a cyclic garbage collection |
1838 | | during interpreter shutdown (and then never finish it). |
1839 | | See http://bugs.python.org/issue8713#msg195178 for an example. |
1840 | | */ |
1841 | 0 | gc_collect_main(tstate, NUM_GENERATIONS - 1, _Py_GC_REASON_SHUTDOWN); |
1842 | 0 | } |
1843 | | |
1844 | | void |
1845 | | _PyGC_DumpShutdownStats(PyInterpreterState *interp) |
1846 | 0 | { |
1847 | 0 | GCState *gcstate = &interp->gc; |
1848 | 0 | if (!(gcstate->debug & _PyGC_DEBUG_SAVEALL) |
1849 | 0 | && gcstate->garbage != NULL && PyList_GET_SIZE(gcstate->garbage) > 0) { |
1850 | 0 | const char *message; |
1851 | 0 | if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) { |
1852 | 0 | message = "gc: %zd uncollectable objects at shutdown"; |
1853 | 0 | } |
1854 | 0 | else { |
1855 | 0 | message = "gc: %zd uncollectable objects at shutdown; " \ |
1856 | 0 | "use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them"; |
1857 | 0 | } |
1858 | | /* PyErr_WarnFormat does too many things and we are at shutdown, |
1859 | | the warnings module's dependencies (e.g. linecache) may be gone |
1860 | | already. */ |
1861 | 0 | if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0, |
1862 | 0 | "gc", NULL, message, |
1863 | 0 | PyList_GET_SIZE(gcstate->garbage))) |
1864 | 0 | { |
1865 | 0 | PyErr_FormatUnraisable("Exception ignored in GC shutdown"); |
1866 | 0 | } |
1867 | 0 | if (gcstate->debug & _PyGC_DEBUG_UNCOLLECTABLE) { |
1868 | 0 | PyObject *repr = NULL, *bytes = NULL; |
1869 | 0 | repr = PyObject_Repr(gcstate->garbage); |
1870 | 0 | if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr))) { |
1871 | 0 | PyErr_FormatUnraisable("Exception ignored in GC shutdown " |
1872 | 0 | "while formatting garbage"); |
1873 | 0 | } |
1874 | 0 | else { |
1875 | 0 | PySys_WriteStderr( |
1876 | 0 | " %s\n", |
1877 | 0 | PyBytes_AS_STRING(bytes) |
1878 | 0 | ); |
1879 | 0 | } |
1880 | 0 | Py_XDECREF(repr); |
1881 | 0 | Py_XDECREF(bytes); |
1882 | 0 | } |
1883 | 0 | } |
1884 | 0 | } |
1885 | | |
1886 | | static void |
1887 | 0 | finalize_unlink_gc_head(PyGC_Head *gc) { |
1888 | 0 | PyGC_Head *prev = GC_PREV(gc); |
1889 | 0 | PyGC_Head *next = GC_NEXT(gc); |
1890 | 0 | _PyGCHead_SET_NEXT(prev, next); |
1891 | 0 | _PyGCHead_SET_PREV(next, prev); |
1892 | 0 | } |
1893 | | |
1894 | | void |
1895 | | _PyGC_Fini(PyInterpreterState *interp) |
1896 | 0 | { |
1897 | 0 | GCState *gcstate = &interp->gc; |
1898 | 0 | Py_CLEAR(gcstate->garbage); |
1899 | 0 | Py_CLEAR(gcstate->callbacks); |
1900 | 0 | PyMem_RawFree(gcstate->generation_stats); |
1901 | 0 | gcstate->generation_stats = NULL; |
1902 | | |
1903 | | /* Prevent a subtle bug that affects sub-interpreters that use basic |
1904 | | * single-phase init extensions (m_size == -1). Those extensions cause objects |
1905 | | * to be shared between interpreters, via the PyDict_Update(mdict, m_copy) call |
1906 | | * in import_find_extension(). |
1907 | | * |
1908 | | * If they are GC objects, their GC head next or prev links could refer to |
1909 | | * the interpreter _gc_runtime_state PyGC_Head nodes. Those nodes go away |
1910 | | * when the interpreter structure is freed and so pointers to them become |
1911 | | * invalid. If those objects are still used by another interpreter and |
1912 | | * UNTRACK is called on them, a crash will happen. We untrack the nodes |
1913 | | * here to avoid that. |
1914 | | * |
1915 | | * This bug was originally fixed when reported as gh-90228. The bug was |
1916 | | * re-introduced in gh-94673. |
1917 | | */ |
1918 | 0 | for (int i = 0; i < NUM_GENERATIONS; i++) { |
1919 | 0 | finalize_unlink_gc_head(&gcstate->generations[i].head); |
1920 | 0 | } |
1921 | 0 | finalize_unlink_gc_head(&gcstate->permanent_generation.head); |
1922 | 0 | } |
1923 | | |
1924 | | /* for debugging */ |
1925 | | void |
1926 | | _PyGC_Dump(PyGC_Head *g) |
1927 | 0 | { |
1928 | 0 | PyObject_Dump(FROM_GC(g)); |
1929 | 0 | } |
1930 | | |
1931 | | |
1932 | | #ifdef Py_DEBUG |
1933 | | static int |
1934 | | visit_validate(PyObject *op, void *parent_raw) |
1935 | | { |
1936 | | PyObject *parent = _PyObject_CAST(parent_raw); |
1937 | | if (_PyObject_IsFreed(op)) { |
1938 | | _PyObject_ASSERT_FAILED_MSG(parent, |
1939 | | "PyObject_GC_Track() object is not valid"); |
1940 | | } |
1941 | | return 0; |
1942 | | } |
1943 | | #endif |
1944 | | |
1945 | | |
1946 | | /* extension modules might be compiled with GC support so these |
1947 | | functions must always be available */ |
1948 | | |
1949 | | void |
1950 | | PyObject_GC_Track(void *op_raw) |
1951 | 165M | { |
1952 | 165M | PyObject *op = _PyObject_CAST(op_raw); |
1953 | 165M | if (_PyObject_GC_IS_TRACKED(op)) { |
1954 | 0 | _PyObject_ASSERT_FAILED_MSG(op, |
1955 | 0 | "object already tracked " |
1956 | 0 | "by the garbage collector"); |
1957 | 0 | } |
1958 | 165M | _PyObject_GC_TRACK(op); |
1959 | | |
1960 | | #ifdef Py_DEBUG |
1961 | | /* Check that the object is valid: validate objects traversed |
1962 | | by tp_traverse() */ |
1963 | | traverseproc traverse = Py_TYPE(op)->tp_traverse; |
1964 | | (void)traverse(op, visit_validate, op); |
1965 | | #endif |
1966 | 165M | } |
1967 | | |
1968 | | void |
1969 | | PyObject_GC_UnTrack(void *op_raw) |
1970 | 1.40G | { |
1971 | 1.40G | PyObject *op = _PyObject_CAST(op_raw); |
1972 | | /* The code for some objects, such as tuples, is a bit |
1973 | | * sloppy about when the object is tracked and untracked. */ |
1974 | 1.40G | if (_PyObject_GC_IS_TRACKED(op)) { |
1975 | 1.19G | _PyObject_GC_UNTRACK(op); |
1976 | 1.19G | } |
1977 | 1.40G | } |
1978 | | |
1979 | | int |
1980 | | PyObject_IS_GC(PyObject *obj) |
1981 | 535M | { |
1982 | 535M | return _PyObject_IS_GC(obj); |
1983 | 535M | } |
1984 | | |
1985 | | void |
1986 | | _Py_ScheduleGC(PyThreadState *tstate) |
1987 | 18.1M | { |
1988 | 18.1M | if (!_Py_eval_breaker_bit_is_set(tstate, _PY_GC_SCHEDULED_BIT)) |
1989 | 127k | { |
1990 | 127k | _Py_set_eval_breaker_bit(tstate, _PY_GC_SCHEDULED_BIT); |
1991 | 127k | } |
1992 | 18.1M | } |
1993 | | |
1994 | | void |
1995 | | _PyObject_GC_Link(PyObject *op) |
1996 | 656M | { |
1997 | 656M | PyGC_Head *gc = AS_GC(op); |
1998 | | // gc must be correctly aligned |
1999 | 656M | _PyObject_ASSERT(op, ((uintptr_t)gc & (sizeof(uintptr_t)-1)) == 0); |
2000 | | |
2001 | 656M | PyThreadState *tstate = _PyThreadState_GET(); |
2002 | 656M | GCState *gcstate = &tstate->interp->gc; |
2003 | 656M | gc->_gc_next = 0; |
2004 | 656M | gc->_gc_prev = 0; |
2005 | 656M | gcstate->generations[0].count++; /* number of allocated GC objects */ |
2006 | 656M | if (gcstate->generations[0].count > gcstate->generations[0].threshold && |
2007 | 18.1M | gcstate->enabled && |
2008 | 18.1M | gcstate->generations[0].threshold && |
2009 | 18.1M | !_Py_atomic_load_int_relaxed(&gcstate->collecting) && |
2010 | 18.1M | !_PyErr_Occurred(tstate)) |
2011 | 18.1M | { |
2012 | 18.1M | _Py_ScheduleGC(tstate); |
2013 | 18.1M | } |
2014 | 656M | } |
2015 | | |
2016 | | void |
2017 | | _Py_RunGC(PyThreadState *tstate) |
2018 | 127k | { |
2019 | 127k | GCState *gcstate = get_gc_state(); |
2020 | 127k | if (!gcstate->enabled) { |
2021 | 0 | return; |
2022 | 0 | } |
2023 | 127k | gc_collect_main(tstate, GENERATION_AUTO, _Py_GC_REASON_HEAP); |
2024 | 127k | } |
2025 | | |
2026 | | static PyObject * |
2027 | | gc_alloc(PyTypeObject *tp, size_t basicsize, size_t presize) |
2028 | 523M | { |
2029 | 523M | PyThreadState *tstate = _PyThreadState_GET(); |
2030 | 523M | if (basicsize > PY_SSIZE_T_MAX - presize) { |
2031 | 0 | return _PyErr_NoMemory(tstate); |
2032 | 0 | } |
2033 | 523M | size_t size = presize + basicsize; |
2034 | 523M | char *mem = _PyObject_MallocWithType(tp, size); |
2035 | 523M | if (mem == NULL) { |
2036 | 0 | return _PyErr_NoMemory(tstate); |
2037 | 0 | } |
2038 | 523M | ((PyObject **)mem)[0] = NULL; |
2039 | 523M | ((PyObject **)mem)[1] = NULL; |
2040 | 523M | PyObject *op = (PyObject *)(mem + presize); |
2041 | 523M | _PyObject_GC_Link(op); |
2042 | 523M | return op; |
2043 | 523M | } |
2044 | | |
2045 | | |
2046 | | PyObject * |
2047 | | _PyObject_GC_New(PyTypeObject *tp) |
2048 | 261M | { |
2049 | 261M | size_t presize = _PyType_PreHeaderSize(tp); |
2050 | 261M | size_t size = _PyObject_SIZE(tp); |
2051 | 261M | if (_PyType_HasFeature(tp, Py_TPFLAGS_INLINE_VALUES)) { |
2052 | 236 | size += _PyInlineValuesSize(tp); |
2053 | 236 | } |
2054 | 261M | PyObject *op = gc_alloc(tp, size, presize); |
2055 | 261M | if (op == NULL) { |
2056 | 0 | return NULL; |
2057 | 0 | } |
2058 | 261M | _PyObject_Init(op, tp); |
2059 | 261M | if (tp->tp_flags & Py_TPFLAGS_INLINE_VALUES) { |
2060 | 236 | _PyObject_InitInlineValues(op, tp); |
2061 | 236 | } |
2062 | 261M | return op; |
2063 | 261M | } |
2064 | | |
2065 | | PyVarObject * |
2066 | | _PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems) |
2067 | 262M | { |
2068 | 262M | PyVarObject *op; |
2069 | | |
2070 | 262M | if (nitems < 0) { |
2071 | 0 | PyErr_BadInternalCall(); |
2072 | 0 | return NULL; |
2073 | 0 | } |
2074 | 262M | size_t presize = _PyType_PreHeaderSize(tp); |
2075 | 262M | size_t size = _PyObject_VAR_SIZE(tp, nitems); |
2076 | 262M | op = (PyVarObject *)gc_alloc(tp, size, presize); |
2077 | 262M | if (op == NULL) { |
2078 | 0 | return NULL; |
2079 | 0 | } |
2080 | 262M | _PyObject_InitVar(op, tp, nitems); |
2081 | 262M | return op; |
2082 | 262M | } |
2083 | | |
2084 | | PyObject * |
2085 | | PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *tp, size_t extra_size) |
2086 | 0 | { |
2087 | 0 | size_t presize = _PyType_PreHeaderSize(tp); |
2088 | 0 | size_t size = _PyObject_SIZE(tp) + extra_size; |
2089 | 0 | PyObject *op = gc_alloc(tp, size, presize); |
2090 | 0 | if (op == NULL) { |
2091 | 0 | return NULL; |
2092 | 0 | } |
2093 | 0 | memset((char *)op + sizeof(PyObject), 0, size - sizeof(PyObject)); |
2094 | 0 | _PyObject_Init(op, tp); |
2095 | 0 | return op; |
2096 | 0 | } |
2097 | | |
2098 | | PyVarObject * |
2099 | | _PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems) |
2100 | 41 | { |
2101 | 41 | const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems); |
2102 | 41 | const size_t presize = _PyType_PreHeaderSize(Py_TYPE(op)); |
2103 | 41 | _PyObject_ASSERT((PyObject *)op, !_PyObject_GC_IS_TRACKED(op)); |
2104 | 41 | if (basicsize > (size_t)PY_SSIZE_T_MAX - presize) { |
2105 | 0 | return (PyVarObject *)PyErr_NoMemory(); |
2106 | 0 | } |
2107 | 41 | char *mem = (char *)op - presize; |
2108 | 41 | mem = (char *)_PyObject_ReallocWithType(Py_TYPE(op), mem, presize + basicsize); |
2109 | 41 | if (mem == NULL) { |
2110 | 0 | return (PyVarObject *)PyErr_NoMemory(); |
2111 | 0 | } |
2112 | 41 | op = (PyVarObject *) (mem + presize); |
2113 | 41 | Py_SET_SIZE(op, nitems); |
2114 | 41 | return op; |
2115 | 41 | } |
2116 | | |
2117 | | void |
2118 | | PyObject_GC_Del(void *op) |
2119 | 655M | { |
2120 | 655M | size_t presize = _PyType_PreHeaderSize(Py_TYPE(op)); |
2121 | 655M | PyGC_Head *g = AS_GC(op); |
2122 | 655M | if (_PyObject_GC_IS_TRACKED(op)) { |
2123 | 0 | gc_list_remove(g); |
2124 | 0 | GCState *gcstate = get_gc_state(); |
2125 | 0 | gcstate->heap_size--; |
2126 | | #ifdef Py_DEBUG |
2127 | | PyObject *exc = PyErr_GetRaisedException(); |
2128 | | if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0, |
2129 | | "gc", NULL, |
2130 | | "Object of type %s is not untracked " |
2131 | | "before destruction", |
2132 | | Py_TYPE(op)->tp_name)) |
2133 | | { |
2134 | | PyErr_FormatUnraisable("Exception ignored on object deallocation"); |
2135 | | } |
2136 | | PyErr_SetRaisedException(exc); |
2137 | | #endif |
2138 | 0 | } |
2139 | 655M | GCState *gcstate = get_gc_state(); |
2140 | 655M | if (gcstate->generations[0].count > 0) { |
2141 | 425M | gcstate->generations[0].count--; |
2142 | 425M | } |
2143 | 655M | PyObject_Free(((char *)op)-presize); |
2144 | 655M | } |
2145 | | |
2146 | | int |
2147 | | PyObject_GC_IsTracked(PyObject* obj) |
2148 | 8.97k | { |
2149 | 8.97k | if (_PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj)) { |
2150 | 32 | return 1; |
2151 | 32 | } |
2152 | 8.93k | return 0; |
2153 | 8.97k | } |
2154 | | |
2155 | | int |
2156 | | PyObject_GC_IsFinalized(PyObject *obj) |
2157 | 0 | { |
2158 | 0 | if (_PyObject_IS_GC(obj) && _PyGC_FINALIZED(obj)) { |
2159 | 0 | return 1; |
2160 | 0 | } |
2161 | 0 | return 0; |
2162 | 0 | } |
2163 | | |
2164 | | static int |
2165 | | visit_generation(gcvisitobjects_t callback, void *arg, struct gc_generation *gen) |
2166 | 0 | { |
2167 | 0 | PyGC_Head *gc_list, *gc; |
2168 | 0 | gc_list = &gen->head; |
2169 | 0 | for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) { |
2170 | 0 | PyObject *op = FROM_GC(gc); |
2171 | 0 | Py_INCREF(op); |
2172 | 0 | int res = callback(op, arg); |
2173 | 0 | Py_DECREF(op); |
2174 | 0 | if (!res) { |
2175 | 0 | return -1; |
2176 | 0 | } |
2177 | 0 | } |
2178 | 0 | return 0; |
2179 | 0 | } |
2180 | | |
2181 | | void |
2182 | | PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg) |
2183 | 0 | { |
2184 | 0 | GCState *gcstate = get_gc_state(); |
2185 | 0 | int original_state = gcstate->enabled; |
2186 | 0 | gcstate->enabled = 0; |
2187 | 0 | for (size_t i = 0; i < NUM_GENERATIONS; i++) { |
2188 | 0 | if (visit_generation(callback, arg, &gcstate->generations[i]) < 0) { |
2189 | 0 | goto done; |
2190 | 0 | } |
2191 | 0 | } |
2192 | 0 | visit_generation(callback, arg, &gcstate->permanent_generation); |
2193 | 0 | done: |
2194 | 0 | gcstate->enabled = original_state; |
2195 | 0 | } |
2196 | | |
2197 | | #endif // !Py_GIL_DISABLED |