]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.8] bpo-39453: Fix contains method of list to hold strong references (GH-18204)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Mon, 17 Feb 2020 09:30:44 +0000 (01:30 -0800)
committerGitHub <noreply@github.com>
Mon, 17 Feb 2020 09:30:44 +0000 (01:30 -0800)
(cherry picked from commit f64abd10563c25a94011f9e3335fd8a1cf47c205)

Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
Lib/test/test_list.py
Misc/NEWS.d/next/Core and Builtins/2020-01-25-23-51-17.bpo-39453.xCOkYk.rst [new file with mode: 0644]
Objects/listobject.c

index 553ac8c1cef81137f43f5496a15d135e84f21d76..32bf17564c9d9bff6316de909596dc0f17972ea1 100644 (file)
@@ -212,6 +212,13 @@ class ListTest(list_tests.CommonTest):
         with self.assertRaises(ValueError):
             lst.remove(lst)
 
+        # bpo-39453: list.__contains__ was not holding strong references
+        # to list elements while calling PyObject_RichCompareBool().
+        lst = [X(), X()]
+        3 in lst
+        lst = [X(), X()]
+        X() in lst
+
 
 if __name__ == "__main__":
     unittest.main()
diff --git a/Misc/NEWS.d/next/Core and Builtins/2020-01-25-23-51-17.bpo-39453.xCOkYk.rst b/Misc/NEWS.d/next/Core and Builtins/2020-01-25-23-51-17.bpo-39453.xCOkYk.rst
new file mode 100644 (file)
index 0000000..8c2e49f
--- /dev/null
@@ -0,0 +1,2 @@
+Fixed a possible crash in :meth:`list.__contains__` when a list is changed
+during comparing items. Patch by Dong-hee Na.
index 856f3215e88553411e2cbee72b96aa97fde70943..158ca11d03299406d4699d89d32c14abc76a9d19 100644 (file)
@@ -397,12 +397,16 @@ list_length(PyListObject *a)
 static int
 list_contains(PyListObject *a, PyObject *el)
 {
+    PyObject *item;
     Py_ssize_t i;
     int cmp;
 
-    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
-        cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
-                                           Py_EQ);
+    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
+        item = PyList_GET_ITEM(a, i);
+        Py_INCREF(item);
+        cmp = PyObject_RichCompareBool(el, item, Py_EQ);
+        Py_DECREF(item);
+    }
     return cmp;
 }