Skip to content

Commit 3fd46c3

Browse files
committed
Attempt to make _PyForIter_NextWithIndex thread safe.
1 parent f43ccc3 commit 3fd46c3

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

Include/internal/pycore_stackref.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,9 @@ PyStackRef_LongCheck(_PyStackRef stackref)
741741
static inline bool
742742
PyStackRef_ExceptionInstanceCheck(_PyStackRef stackref)
743743
{
744+
if (PyStackRef_IsTaggedInt(stackref)) {
745+
return false;
746+
}
744747
return PyExceptionInstance_Check(PyStackRef_AsPyObjectBorrow(stackref));
745748
}
746749

Python/ceval.c

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3421,14 +3421,28 @@ _PyStackRef
34213421
_PyForIter_NextWithIndex(PyObject *seq, _PyStackRef index)
34223422
{
34233423
assert(PyStackRef_IsTaggedInt(index));
3424-
assert(Py_TYPE(seq) == &PyTuple_Type || Py_TYPE(seq) == &PyList_Type);
3425-
size_t size = Py_SIZE(seq);
3424+
assert(PyTuple_CheckExact(seq) || PyList_CheckExact(seq));
34263425
intptr_t i = PyStackRef_UntagInt(index);
3426+
if (PyTuple_CheckExact(seq)) {
3427+
size_t size = PyTuple_GET_SIZE(seq);
3428+
if ((size_t)i >= size) {
3429+
return PyStackRef_NULL;
3430+
}
3431+
return PyStackRef_FromPyObjectNew(PyTuple_GET_ITEM(seq, i));
3432+
}
3433+
size_t size = PyList_GET_SIZE(seq);
34273434
if ((size_t)i >= size) {
34283435
return PyStackRef_NULL;
34293436
}
3430-
PyObject *next_o = PySequence_Fast_GET_ITEM(seq, i);
3431-
return PyStackRef_FromPyObjectNew(next_o);
3437+
#ifdef Py_GIL_DISABLED
3438+
PyObject *item = _PyList_GetItemRef((PyListObject *)seq, i);
3439+
if (item == NULL) {
3440+
return PyStackRef_NULL;
3441+
}
3442+
return PyStackRef_FromPyObjectSteal(item);
3443+
#else
3444+
return PyStackRef_FromPyObjectNew(PyList_GET_ITEM(seq, i));
3445+
#endif
34323446
}
34333447

34343448
/* Check if a 'cls' provides the given special method. */

0 commit comments

Comments
 (0)