Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-126312: Don't traverse frozen objects on the free-threaded build #126338

Merged
merged 17 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Lib/test/test_gc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,37 @@ def __del__(self):
gc.collect()
self.assertTrue(collected)

def test_traverse_frozen_objects(self):
# See GH-126312: Objects that were not frozen could traverse over
# a frozen object on the free-threaded build, which would cause
# a negative reference count.
import textwrap
ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved

x = [1, 2, 3]
gc.freeze()
y = [x]
y.append(y)
del y
gc.collect()
gc.unfreeze()
ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved

source = textwrap.dedent("""
import gc
ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved
import unittest


class Test(unittest.TestCase):
def test_something(self):
gc.freeze()
gc.collect()
gc.unfreeze()


if __name__ == "__main__":
unittest.main()
""")
assert_python_ok("-c", source)


class IncrementalGCTests(unittest.TestCase):

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix crash during garbage collection on an object frozen by :func:`gc.freeze` on the
free-threaded build.
8 changes: 6 additions & 2 deletions Python/gc_free_threading.c
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,8 @@ gc_visit_stackref(_PyStackRef stackref)
// being dead already.
if (PyStackRef_IsDeferred(stackref) && !PyStackRef_IsNull(stackref)) {
PyObject *obj = PyStackRef_AsPyObjectBorrow(stackref);
if (_PyObject_GC_IS_TRACKED(obj)) {
if (_PyObject_GC_IS_TRACKED(obj)
&& (obj->ob_gc_bits & _PyGC_BITS_FROZEN) == 0) {
ZeroIntensity marked this conversation as resolved.
Show resolved Hide resolved
gc_add_refs(obj, 1);
}
}
Expand Down Expand Up @@ -439,7 +440,10 @@ process_delayed_frees(PyInterpreterState *interp)
static int
visit_decref(PyObject *op, void *arg)
{
if (_PyObject_GC_IS_TRACKED(op) && !_Py_IsImmortal(op)) {
if (_PyObject_GC_IS_TRACKED(op)
&& !_Py_IsImmortal(op)
&& (op->ob_gc_bits & _PyGC_BITS_FROZEN) == 0)
{
// If update_refs hasn't reached this object yet, mark it
// as (tentatively) unreachable and initialize ob_tid to zero.
gc_maybe_init_refs(op);
Expand Down
Loading