[issue36218] .sort() segfaults consistently on crafted input

Rémi Lapeyre report at bugs.python.org
Wed Mar 6 18:09:43 EST 2019


Rémi Lapeyre <remi.lapeyre at henki.fr> added the comment:

Hi @xtreak, sorry for that.

I think the issue may come from https://github.com/python/cpython/blob/master/Objects/listobject.c#L2273-L2357 where ms.key_compare is set, the conditions on the first ifs looks weird to me and I suspect ms.key_compare is set to unsafe_tuple_compare when not all elements are tuples.


The following patch fixed the issue and made the whole test suite pass:

diff --git Objects/listobject.c Objects/listobject.c
index b6524e8bd7..5237542092 100644
--- Objects/listobject.c
+++ Objects/listobject.c
@@ -1,4 +1,4 @@
-/* List object implementation */
+    /* List object implementation */
 
 #include "Python.h"
 #include "pycore_object.h"
@@ -2338,21 +2338,21 @@ list_sort_impl(PyListObject *self, PyObject *keyfunc, int reverse)
             else {
                 ms.key_compare = safe_object_compare;
             }
+            if (keys_are_in_tuples) {
+                /* Make sure we're not dealing with tuples of tuples
+                * (remember: here, key_type refers list [key[0] for key in keys]) */
+                if (key_type == &PyTuple_Type)
+                    ms.tuple_elem_compare = safe_object_compare;
+                else
+                    ms.tuple_elem_compare = ms.key_compare;
+
+                ms.key_compare = unsafe_tuple_compare;
+            }
         }
         else {
             ms.key_compare = safe_object_compare;
         }
 
-        if (keys_are_in_tuples) {
-            /* Make sure we're not dealing with tuples of tuples
-             * (remember: here, key_type refers list [key[0] for key in keys]) */
-            if (key_type == &PyTuple_Type)
-                ms.tuple_elem_compare = safe_object_compare;
-            else
-                ms.tuple_elem_compare = ms.key_compare;
-
-            ms.key_compare = unsafe_tuple_compare;
-        }
     }
     /* End of pre-sort check: ms is now set properly! */
 


I will have another look at it tomorrow and try to open a pull request.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36218>
_______________________________________


More information about the Python-bugs-list mailing list