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-115874: Don't use module state in teedataobject tp_dealloc #116204

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 9 additions & 1 deletion Lib/test/test_itertools.py
@@ -1,7 +1,7 @@
import doctest
import unittest
from test import support
from test.support import threading_helper
from test.support import threading_helper, script_helper
from itertools import *
import weakref
from decimal import Decimal
Expand Down Expand Up @@ -1699,6 +1699,14 @@ def test_tee(self):
self.pickletest(proto, a, compare=ans)
self.pickletest(proto, b, compare=ans)

def test_tee_dealloc_segfault(self):
# gh-115874: segfaults when accessing module state in tp_dealloc.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@brandtbucher, how about this:

Suggested change
# gh-115874: segfaults when accessing module state in tp_dealloc.
# gh-115874: Segfault when accessing module state in tp_dealloc.
# The repro depends on multiple ref cycles; by importing
# typing, we implicitly create ref cycles between typing
# and copyreg. Without these cycles, the reproducer does
# not work.

script = (
"import typing, copyreg, itertools; "
"copyreg.buggy_tee = itertools.tee(())"
)
script_helper.assert_python_ok("-c", script)

# Issue 13454: Crash when deleting backward iterator from tee()
def test_tee_del_backward(self):
forward, backward = tee(repeat(None, 20000000))
Expand Down
8 changes: 3 additions & 5 deletions Modules/itertoolsmodule.c
Expand Up @@ -815,10 +815,9 @@ teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg)
}

static void
teedataobject_safe_decref(PyObject *obj, PyTypeObject *tdo_type)
teedataobject_safe_decref(PyObject *obj)
{
while (obj && Py_IS_TYPE(obj, tdo_type) &&
Py_REFCNT(obj) == 1) {
while (obj && Py_REFCNT(obj) == 1) {
PyObject *nextlink = ((teedataobject *)obj)->nextlink;
((teedataobject *)obj)->nextlink = NULL;
Py_SETREF(obj, nextlink);
Expand All @@ -837,8 +836,7 @@ teedataobject_clear(teedataobject *tdo)
Py_CLEAR(tdo->values[i]);
tmp = tdo->nextlink;
tdo->nextlink = NULL;
itertools_state *state = get_module_state_by_cls(Py_TYPE(tdo));
teedataobject_safe_decref(tmp, state->teedataobject_type);
teedataobject_safe_decref(tmp);
return 0;
}

Expand Down