Skip to content

Commit 1305832

Browse files
authored
gh-89653: Add assertions on PyUnicode_READ() index (#92883)
Add assertions on the index argument of PyUnicode_READ(), PyUnicode_READ_CHAR() and PyUnicode_WRITE() functions.
1 parent e6fd799 commit 1305832

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

Include/cpython/unicodeobject.h

+9-1
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ static inline Py_ssize_t PyUnicode_GET_LENGTH(PyObject *op) {
304304
static inline void PyUnicode_WRITE(int kind, void *data,
305305
Py_ssize_t index, Py_UCS4 value)
306306
{
307+
assert(index >= 0);
307308
if (kind == PyUnicode_1BYTE_KIND) {
308309
assert(value <= 0xffU);
309310
_Py_STATIC_CAST(Py_UCS1*, data)[index] = _Py_STATIC_CAST(Py_UCS1, value);
@@ -329,6 +330,7 @@ static inline void PyUnicode_WRITE(int kind, void *data,
329330
static inline Py_UCS4 PyUnicode_READ(int kind,
330331
const void *data, Py_ssize_t index)
331332
{
333+
assert(index >= 0);
332334
if (kind == PyUnicode_1BYTE_KIND) {
333335
return _Py_STATIC_CAST(const Py_UCS1*, data)[index];
334336
}
@@ -351,7 +353,13 @@ static inline Py_UCS4 PyUnicode_READ(int kind,
351353
cache kind and use PyUnicode_READ instead. */
352354
static inline Py_UCS4 PyUnicode_READ_CHAR(PyObject *unicode, Py_ssize_t index)
353355
{
354-
int kind = PyUnicode_KIND(unicode);
356+
int kind;
357+
358+
assert(index >= 0);
359+
// Tolerate reading the NUL character at str[len(str)]
360+
assert(index <= PyUnicode_GET_LENGTH(unicode));
361+
362+
kind = PyUnicode_KIND(unicode);
355363
if (kind == PyUnicode_1BYTE_KIND) {
356364
return PyUnicode_1BYTE_DATA(unicode)[index];
357365
}

0 commit comments

Comments
 (0)