Skip to content

Commit

Permalink
PyList_GET_ITEM() now checks the index
Browse files Browse the repository at this point in the history
  • Loading branch information
vstinner committed Jun 27, 2023
1 parent 6b5166f commit 255edc3
Show file tree
Hide file tree
Showing 4 changed files with 12 additions and 3 deletions.
6 changes: 6 additions & 0 deletions Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,12 @@ New Features
``NULL`` if the referent is no longer live.
(Contributed by Victor Stinner in :gh:`105927`.)

* In debug mode and on :option:`Python built with assertions <--with-assertions>`,
:c:func:`PyList_GET_ITEM` now checks the index with an assertion.
If the assertion fails, make sure that the list size is set before calling
:c:func:`PyList_GET_ITEM`.
(Contributed by Victor Stinner.)

Porting to Python 3.13
----------------------

Expand Down
2 changes: 2 additions & 0 deletions Include/cpython/listobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ static inline Py_ssize_t PyList_GET_SIZE(PyObject *op) {
static inline void
PyList_SET_ITEM(PyObject *op, Py_ssize_t index, PyObject *value) {
PyListObject *list = _PyList_CAST(op);
assert(0 <= index);
assert(index < Py_SIZE(list));
list->ob_item[index] = value;
}
#define PyList_SET_ITEM(op, index, value) \
Expand Down
2 changes: 1 addition & 1 deletion Include/internal/pycore_list.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ _PyList_AppendTakeRef(PyListObject *self, PyObject *newitem)
Py_ssize_t allocated = self->allocated;
assert((size_t)len + 1 < PY_SSIZE_T_MAX);
if (allocated > len) {
PyList_SET_ITEM(self, len, newitem);
Py_SET_SIZE(self, len + 1);
PyList_SET_ITEM(self, len, newitem);
return 0;
}
return _PyList_AppendTakeRefListResize(self, newitem);
Expand Down
5 changes: 3 additions & 2 deletions Objects/listobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -953,8 +953,9 @@ list_extend(PyListObject *self, PyObject *iterable)
}
if (Py_SIZE(self) < self->allocated) {
/* steals ref */
PyList_SET_ITEM(self, Py_SIZE(self), item);
Py_SET_SIZE(self, Py_SIZE(self) + 1);
Py_ssize_t len = Py_SIZE(self);
Py_SET_SIZE(self, len + 1);
PyList_SET_ITEM(self, len, item);
}
else {
if (_PyList_AppendTakeRef(self, item) < 0)
Expand Down

0 comments on commit 255edc3

Please sign in to comment.