[3.8] bpo-38588: Fix possible crashes in dict and list when calling P… (GH-17764)

* [3.8] bpo-38588: Fix possible crashes in dict and list when calling PyObject_RichCompareBool (GH-17734)

Take strong references before calling PyObject_RichCompareBool to protect against the case
where the object dies during the call.
(cherry picked from commit 2d5bf568eaa5059402ccce9ba5a366986ba27c8a)

Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>

* Update Objects/listobject.c

@methane's suggestion

Co-Authored-By: Inada Naoki <songofacandy@gmail.com>

Co-authored-by: Inada Naoki <songofacandy@gmail.com>
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 5b51376..de483ab 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -1221,7 +1221,7 @@
         support.check_free_after_iterating(self, lambda d: iter(d.items()), dict)
 
     def test_equal_operator_modifying_operand(self):
-        # test fix for seg fault reported in issue 27945 part 3.
+        # test fix for seg fault reported in bpo-27945 part 3.
         class X():
             def __del__(self):
                 dict_b.clear()
@@ -1237,6 +1237,16 @@
         dict_b = {X(): X()}
         self.assertTrue(dict_a == dict_b)
 
+        # test fix for seg fault reported in bpo-38588 part 1.
+        class Y:
+            def __eq__(self, other):
+                dict_d.clear()
+                return True
+
+        dict_c = {0: Y()}
+        dict_d = {0: set()}
+        self.assertTrue(dict_c == dict_d)
+
     def test_fromkeys_operator_modifying_dict_operand(self):
         # test fix for seg fault reported in issue 27945 part 4a.
         class X(int):
diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 55c6eed..f4dcced 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -158,6 +158,31 @@
         with self.assertRaises(TypeError):
             (3,) + L([1,2])
 
+    def test_equal_operator_modifying_operand(self):
+        # test fix for seg fault reported in bpo-38588 part 2.
+        class X:
+            def __eq__(self,other) :
+                list2.clear()
+                return NotImplemented
+
+        class Y:
+            def __eq__(self, other):
+                list1.clear()
+                return NotImplemented
+
+        class Z:
+            def __eq__(self, other):
+                list3.clear()
+                return NotImplemented
+
+        list1 = [X()]
+        list2 = [Y()]
+        self.assertTrue(list1 == list2)
+
+        list3 = [Z()]
+        list4 = [1]
+        self.assertFalse(list3 == list4)
+
     @cpython_only
     def test_preallocation(self):
         iterable = [0] * 10