Skip to content

Commit dcb68f4

Browse files
authored
bpo-35961: Fix a crash in slice_richcompare() (GH-11830)
Fix a crash in slice_richcompare(): use strong references rather than stolen references for the two temporary internal tuples. The crash (or assertion error) occurred if a garbage collection occurred during slice_richcompare(), especially while calling PyObject_RichCompare(t1, t2, op).
1 parent 5680f65 commit dcb68f4

File tree

2 files changed

+16
-24
lines changed

2 files changed

+16
-24
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a crash in slice_richcompare(): use strong references rather than stolen
2+
references for the two temporary internal tuples.

Objects/sliceobject.c

Lines changed: 14 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -565,14 +565,11 @@ static PyMethodDef slice_methods[] = {
565565
static PyObject *
566566
slice_richcompare(PyObject *v, PyObject *w, int op)
567567
{
568-
PyObject *t1;
569-
PyObject *t2;
570-
PyObject *res;
571-
572568
if (!PySlice_Check(v) || !PySlice_Check(w))
573569
Py_RETURN_NOTIMPLEMENTED;
574570

575571
if (v == w) {
572+
PyObject *res;
576573
/* XXX Do we really need this shortcut?
577574
There's a unit test for it, but is that fair? */
578575
switch (op) {
@@ -589,34 +586,27 @@ slice_richcompare(PyObject *v, PyObject *w, int op)
589586
return res;
590587
}
591588

592-
t1 = PyTuple_New(3);
593-
if (t1 == NULL)
589+
590+
PyObject *t1 = PyTuple_Pack(3,
591+
((PySliceObject *)v)->start,
592+
((PySliceObject *)v)->stop,
593+
((PySliceObject *)v)->step);
594+
if (t1 == NULL) {
594595
return NULL;
595-
t2 = PyTuple_New(3);
596+
}
597+
598+
PyObject *t2 = PyTuple_Pack(3,
599+
((PySliceObject *)w)->start,
600+
((PySliceObject *)w)->stop,
601+
((PySliceObject *)w)->step);
596602
if (t2 == NULL) {
597603
Py_DECREF(t1);
598604
return NULL;
599605
}
600606

601-
PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start);
602-
PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop);
603-
PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step);
604-
PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start);
605-
PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop);
606-
PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step);
607-
608-
res = PyObject_RichCompare(t1, t2, op);
609-
610-
PyTuple_SET_ITEM(t1, 0, NULL);
611-
PyTuple_SET_ITEM(t1, 1, NULL);
612-
PyTuple_SET_ITEM(t1, 2, NULL);
613-
PyTuple_SET_ITEM(t2, 0, NULL);
614-
PyTuple_SET_ITEM(t2, 1, NULL);
615-
PyTuple_SET_ITEM(t2, 2, NULL);
616-
607+
PyObject *res = PyObject_RichCompare(t1, t2, op);
617608
Py_DECREF(t1);
618609
Py_DECREF(t2);
619-
620610
return res;
621611
}
622612

0 commit comments

Comments
 (0)