Kaydet (Commit) c9590ad7 authored tarafından Victor Stinner's avatar Victor Stinner

Close #14085: remove assertions from PyUnicode_WRITE macro

Add checks in PyUnicode_WriteChar() and convert PyUnicode_New() assertion to a
test raising a Python exception.
üst d263d185
...@@ -499,17 +499,14 @@ enum PyUnicode_Kind { ...@@ -499,17 +499,14 @@ enum PyUnicode_Kind {
do { \ do { \
switch ((kind)) { \ switch ((kind)) { \
case PyUnicode_1BYTE_KIND: { \ case PyUnicode_1BYTE_KIND: { \
assert(value <= 0xff); \
((Py_UCS1 *)(data))[(index)] = (Py_UCS1)(value); \ ((Py_UCS1 *)(data))[(index)] = (Py_UCS1)(value); \
break; \ break; \
} \ } \
case PyUnicode_2BYTE_KIND: { \ case PyUnicode_2BYTE_KIND: { \
assert(value <= 0xffff); \
((Py_UCS2 *)(data))[(index)] = (Py_UCS2)(value); \ ((Py_UCS2 *)(data))[(index)] = (Py_UCS2)(value); \
break; \ break; \
} \ } \
default: { \ default: { \
assert(value <= 0x10ffff); \
assert((kind) == PyUnicode_4BYTE_KIND); \ assert((kind) == PyUnicode_4BYTE_KIND); \
((Py_UCS4 *)(data))[(index)] = (Py_UCS4)(value); \ ((Py_UCS4 *)(data))[(index)] = (Py_UCS4)(value); \
} \ } \
......
...@@ -998,7 +998,11 @@ PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar) ...@@ -998,7 +998,11 @@ PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
is_sharing = 1; is_sharing = 1;
} }
else { else {
assert(maxchar <= MAX_UNICODE); if (maxchar > MAX_UNICODE) {
PyErr_SetString(PyExc_SystemError,
"invalid maximum character passed to PyUnicode_New");
return NULL;
}
kind_state = PyUnicode_4BYTE_KIND; kind_state = PyUnicode_4BYTE_KIND;
char_size = 4; char_size = 4;
if (sizeof(wchar_t) == 4) if (sizeof(wchar_t) == 4)
...@@ -3931,6 +3935,7 @@ PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index) ...@@ -3931,6 +3935,7 @@ PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
int int
PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch) PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
{ {
Py_UCS4 maxchar;
if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) { if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
PyErr_BadArgument(); PyErr_BadArgument();
return -1; return -1;
...@@ -3942,6 +3947,10 @@ PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch) ...@@ -3942,6 +3947,10 @@ PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
} }
if (unicode_check_modifiable(unicode)) if (unicode_check_modifiable(unicode))
return -1; return -1;
if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
PyErr_SetString(PyExc_ValueError, "character out of range");
return -1;
}
PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode), PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
index, ch); index, ch);
return 0; return 0;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment