[Python-checkins] bpo-39453: Make list.__contains__ hold strong references to avoid crashes (GH-18181)

Pablo Galindo webhook-mailer at python.org
Mon Jan 27 10:02:28 EST 2020


https://github.com/python/cpython/commit/4dbf2d8c6789a9b7299b142033073213604b8fdc
commit: 4dbf2d8c6789a9b7299b142033073213604b8fdc
branch: master
author: Dong-hee Na <donghee.na92 at gmail.com>
committer: Pablo Galindo <Pablogsal at gmail.com>
date: 2020-01-27T15:02:23Z
summary:

bpo-39453: Make list.__contains__ hold strong references to avoid crashes (GH-18181)

files:
A Misc/NEWS.d/next/Core and Builtins/2020-01-25-23-51-17.bpo-39453.xCOkYk.rst
M Lib/test/test_list.py
M Objects/listobject.c

diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 6e3c4c109300e..33a55f76d9b2c 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -221,6 +221,11 @@ def __eq__(self, other):
         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
+
 
 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
index 0000000000000..8c2e49f9474c4
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2020-01-25-23-51-17.bpo-39453.xCOkYk.rst	
@@ -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.
diff --git a/Objects/listobject.c b/Objects/listobject.c
index a4e90dbf90cf9..38055d5f5f341 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -445,11 +445,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)
+    for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i) {
+        item = PyList_GET_ITEM(a, i);
+        Py_INCREF(item);
         cmp = PyObject_RichCompareBool(PyList_GET_ITEM(a, i), el, Py_EQ);
+        Py_DECREF(item);
+    }
     return cmp;
 }
 



More information about the Python-checkins mailing list