Issue #13454: Fix a crash when deleting an iterator created by itertools.tee()
if all other iterators were very advanced before.
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index ccdbf8a..6f933c5 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -906,6 +906,14 @@
del a
self.assertRaises(ReferenceError, getattr, p, '__class__')
+ # Issue 13454: Crash when deleting backward iterator from tee()
+ def test_tee_del_backward(self):
+ forward, backward = tee(xrange(20000000))
+ for i in forward:
+ pass
+
+ del backward
+
def test_StopIteration(self):
self.assertRaises(StopIteration, izip().next)
diff --git a/Misc/NEWS b/Misc/NEWS
index ce4f35f..8d84806 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -189,6 +189,9 @@
Library
-------
+- Issue #13454: Fix a crash when deleting an iterator created by itertools.tee()
+ if all other iterators were very advanced before.
+
- Issue #1159051: GzipFile now raises EOFError when reading a corrupted file
with truncated header or footer.
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index f6d0e23..ea82291 100644
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -401,14 +401,31 @@
return 0;
}
+static void
+teedataobject_safe_decref(PyObject *obj)
+{
+ while (obj && Py_TYPE(obj) == &teedataobject_type &&
+ Py_REFCNT(obj) == 1) {
+ PyObject *nextlink = ((teedataobject *)obj)->nextlink;
+ ((teedataobject *)obj)->nextlink = NULL;
+ Py_DECREF(obj);
+ obj = nextlink;
+ }
+ Py_XDECREF(obj);
+}
+
static int
teedataobject_clear(teedataobject *tdo)
{
int i;
+ PyObject *tmp;
+
Py_CLEAR(tdo->it);
for (i=0 ; i<tdo->numread ; i++)
Py_CLEAR(tdo->values[i]);
- Py_CLEAR(tdo->nextlink);
+ tmp = tdo->nextlink;
+ tdo->nextlink = NULL;
+ teedataobject_safe_decref(tmp);
return 0;
}
@@ -475,6 +492,8 @@
if (to->index >= LINKCELLS) {
link = teedataobject_jumplink(to->dataobj);
+ if (link == NULL)
+ return NULL;
Py_DECREF(to->dataobj);
to->dataobj = (teedataobject *)link;
to->index = 0;