Skip to content

Commit 35ccf67

Browse files
naschemesergey-miryanov
authored andcommitted
[3.14] GH-91636: Clear weakrefs created by finalizers. (GH-136401)
Weakrefs to unreachable garbage that are created during running of finalizers need to be cleared. This avoids exposing objects that have `tp_clear` called on them to Python-level code. (cherry picked from commit b6b99bf) Co-authored-by: Neil Schemenauer <nas-github@arctrix.com>
1 parent 360214e commit 35ccf67

File tree

4 files changed

+54
-14
lines changed

4 files changed

+54
-14
lines changed

Lib/test/test_gc.py

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -262,9 +262,11 @@ class Cyclic(tuple):
262262
# finalizer.
263263
def __del__(self):
264264
265-
# 5. Create a weakref to `func` now. If we had created
266-
# it earlier, it would have been cleared by the
267-
# garbage collector before calling the finalizers.
265+
# 5. Create a weakref to `func` now. In previous
266+
# versions of Python, this would avoid having it
267+
# cleared by the garbage collector before calling
268+
# the finalizers. Now, weakrefs get cleared after
269+
# calling finalizers.
268270
self[1].ref = weakref.ref(self[0])
269271
270272
# 6. Drop the global reference to `latefin`. The only
@@ -293,14 +295,18 @@ def func():
293295
# which will find `cyc` and `func` as garbage.
294296
gc.collect()
295297
296-
# 9. Previously, this would crash because `func_qualname`
297-
# had been NULL-ed out by func_clear().
298+
# 9. Previously, this would crash because the weakref
299+
# created in the finalizer revealed the function after
300+
# `tp_clear` was called and `func_qualname`
301+
# had been NULL-ed out by func_clear(). Now, we clear
302+
# weakrefs to unreachable objects before calling `tp_clear`
303+
# but after calling finalizers.
298304
print(f"{func=}")
299305
"""
300-
# We're mostly just checking that this doesn't crash.
301306
rc, stdout, stderr = assert_python_ok("-c", code)
302307
self.assertEqual(rc, 0)
303-
self.assertRegex(stdout, rb"""\A\s*func=<function at \S+>\s*\z""")
308+
# The `func` global is None because the weakref was cleared.
309+
self.assertRegex(stdout, rb"""\A\s*func=None""")
304310
self.assertFalse(stderr)
305311

306312
@refcount_test
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
While performing garbage collection, clear weakrefs to unreachable objects
2+
that are created during running of finalizers. If those weakrefs were are
3+
not cleared, they could reveal unreachable objects.

Python/gc.c

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -870,7 +870,7 @@ move_legacy_finalizer_reachable(PyGC_Head *finalizers)
870870
* no object in `unreachable` is weakly referenced anymore.
871871
*/
872872
static int
873-
handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
873+
handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old, bool allow_callbacks)
874874
{
875875
PyGC_Head *gc;
876876
PyObject *op; /* generally FROM_GC(gc) */
@@ -879,7 +879,9 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
879879
PyGC_Head *next;
880880
int num_freed = 0;
881881

882-
gc_list_init(&wrcb_to_call);
882+
if (allow_callbacks) {
883+
gc_list_init(&wrcb_to_call);
884+
}
883885

884886
/* Clear all weakrefs to the objects in unreachable. If such a weakref
885887
* also has a callback, move it into `wrcb_to_call` if the callback
@@ -935,6 +937,11 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
935937
_PyObject_ASSERT((PyObject *)wr, wr->wr_object == op);
936938
_PyWeakref_ClearRef(wr);
937939
_PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);
940+
941+
if (!allow_callbacks) {
942+
continue;
943+
}
944+
938945
if (wr->wr_callback == NULL) {
939946
/* no callback */
940947
continue;
@@ -987,6 +994,10 @@ handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
987994
}
988995
}
989996

997+
if (!allow_callbacks) {
998+
return 0;
999+
}
1000+
9901001
/* Invoke the callbacks we decided to honor. It's safe to invoke them
9911002
* because they can't reference unreachable objects.
9921003
*/
@@ -1739,7 +1750,7 @@ gc_collect_region(PyThreadState *tstate,
17391750
}
17401751

17411752
/* Clear weakrefs and invoke callbacks as necessary. */
1742-
stats->collected += handle_weakrefs(&unreachable, to);
1753+
stats->collected += handle_weakrefs(&unreachable, to, true);
17431754
gc_list_validate_space(to, gcstate->visited_space);
17441755
validate_list(to, collecting_clear_unreachable_clear);
17451756
validate_list(&unreachable, collecting_set_unreachable_clear);
@@ -1753,6 +1764,14 @@ gc_collect_region(PyThreadState *tstate,
17531764
gc_list_init(&final_unreachable);
17541765
handle_resurrected_objects(&unreachable, &final_unreachable, to);
17551766

1767+
/* Clear weakrefs to objects in the unreachable set. No Python-level
1768+
* code must be allowed to access those unreachable objects. During
1769+
* delete_garbage(), finalizers outside the unreachable set might run
1770+
* and create new weakrefs. If those weakrefs were not cleared, they
1771+
* could reveal unreachable objects. Callbacks are not executed.
1772+
*/
1773+
handle_weakrefs(&final_unreachable, NULL, false);
1774+
17561775
/* Call tp_clear on objects in the final_unreachable set. This will cause
17571776
* the reference cycles to be broken. It may also cause some objects
17581777
* in finalizers to be freed.

Python/gc_free_threading.c

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1520,9 +1520,9 @@ move_legacy_finalizer_reachable(struct collection_state *state)
15201520
}
15211521

15221522
// Clear all weakrefs to unreachable objects. Weakrefs with callbacks are
1523-
// enqueued in `wrcb_to_call`, but not invoked yet.
1523+
// optionally enqueued in `wrcb_to_call`, but not invoked yet.
15241524
static void
1525-
clear_weakrefs(struct collection_state *state)
1525+
clear_weakrefs(struct collection_state *state, bool enqueue_callbacks)
15261526
{
15271527
PyObject *op;
15281528
WORKSTACK_FOR_EACH(&state->unreachable, op) {
@@ -1554,6 +1554,10 @@ clear_weakrefs(struct collection_state *state)
15541554
_PyWeakref_ClearRef(wr);
15551555
_PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);
15561556

1557+
if (!enqueue_callbacks) {
1558+
continue;
1559+
}
1560+
15571561
// We do not invoke callbacks for weakrefs that are themselves
15581562
// unreachable. This is partly for historical reasons: weakrefs
15591563
// predate safe object finalization, and a weakref that is itself
@@ -2249,7 +2253,7 @@ gc_collect_internal(PyInterpreterState *interp, struct collection_state *state,
22492253
}
22502254

22512255
// Clear weakrefs and enqueue callbacks (but do not call them).
2252-
clear_weakrefs(state);
2256+
clear_weakrefs(state, true);
22532257
_PyEval_StartTheWorld(interp);
22542258

22552259
// Deallocate any object from the refcount merge step
@@ -2260,11 +2264,19 @@ gc_collect_internal(PyInterpreterState *interp, struct collection_state *state,
22602264
call_weakref_callbacks(state);
22612265
finalize_garbage(state);
22622266

2263-
// Handle any objects that may have resurrected after the finalization.
22642267
_PyEval_StopTheWorld(interp);
2268+
// Handle any objects that may have resurrected after the finalization.
22652269
err = handle_resurrected_objects(state);
22662270
// Clear free lists in all threads
22672271
_PyGC_ClearAllFreeLists(interp);
2272+
if (err == 0) {
2273+
// Clear weakrefs to objects in the unreachable set. No Python-level
2274+
// code must be allowed to access those unreachable objects. During
2275+
// delete_garbage(), finalizers outside the unreachable set might
2276+
// run and create new weakrefs. If those weakrefs were not cleared,
2277+
// they could reveal unreachable objects.
2278+
clear_weakrefs(state, false);
2279+
}
22682280
// Record the number of live GC objects
22692281
interp->gc.long_lived_total = state->long_lived_total;
22702282
_PyEval_StartTheWorld(interp);

0 commit comments

Comments
 (0)