Skip to content

gh-89653: Add assertions on PyUnicode_READ() index #92883

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 17, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion Include/cpython/unicodeobject.h
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ static inline Py_ssize_t PyUnicode_GET_LENGTH(PyObject *op) {
static inline void PyUnicode_WRITE(int kind, void *data,
Py_ssize_t index, Py_UCS4 value)
{
assert(index >= 0);
if (kind == PyUnicode_1BYTE_KIND) {
assert(value <= 0xffU);
_Py_STATIC_CAST(Py_UCS1*, data)[index] = _Py_STATIC_CAST(Py_UCS1, value);
Expand All @@ -329,6 +330,7 @@ static inline void PyUnicode_WRITE(int kind, void *data,
static inline Py_UCS4 PyUnicode_READ(int kind,
const void *data, Py_ssize_t index)
{
assert(index >= 0);
if (kind == PyUnicode_1BYTE_KIND) {
return _Py_STATIC_CAST(const Py_UCS1*, data)[index];
}
Expand All @@ -350,7 +352,13 @@ static inline Py_UCS4 PyUnicode_READ(int kind,
cache kind and use PyUnicode_READ instead. */
static inline Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
{
int kind = PyUnicode_KIND(unicode);
int kind;

assert(index >= 0);
// Tolerate reading the NUL character at str[len(str)]
assert(index <= PyUnicode_GET_LENGTH(unicode));

kind = PyUnicode_KIND(unicode);
if (kind == PyUnicode_1BYTE_KIND) {
return PyUnicode_1BYTE_DATA(unicode)[index];
}
Expand Down