Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b0541f4

Browse files
committed
Issue #29145: Fix overflow checks in str.replace() and str.join().
Based on patch by Martin Panter.
1 parent 18e0a97 commit b0541f4

1 file changed

Lines changed: 8 additions & 6 deletions

File tree

Objects/unicodeobject.c

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9752,7 +9752,7 @@ PyUnicode_Join(PyObject *separator, PyObject *seq)
97529752
use_memcpy = 1;
97539753
#endif
97549754
for (i = 0; i < seqlen; i++) {
9755-
const Py_ssize_t old_sz = sz;
9755+
size_t add_sz;
97569756
item = items[i];
97579757
if (!PyUnicode_Check(item)) {
97589758
PyErr_Format(PyExc_TypeError,
@@ -9763,16 +9763,18 @@ PyUnicode_Join(PyObject *separator, PyObject *seq)
97639763
}
97649764
if (PyUnicode_READY(item) == -1)
97659765
goto onError;
9766-
sz += PyUnicode_GET_LENGTH(item);
9766+
add_sz = PyUnicode_GET_LENGTH(item);
97679767
item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
97689768
maxchar = Py_MAX(maxchar, item_maxchar);
9769-
if (i != 0)
9770-
sz += seplen;
9771-
if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9769+
if (i != 0) {
9770+
add_sz += seplen;
9771+
}
9772+
if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
97729773
PyErr_SetString(PyExc_OverflowError,
97739774
"join() result is too long for a Python string");
97749775
goto onError;
97759776
}
9777+
sz += add_sz;
97769778
if (use_memcpy && last_obj != NULL) {
97779779
if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
97789780
use_memcpy = 0;
@@ -10418,7 +10420,7 @@ replace(PyObject *self, PyObject *str1,
1041810420
u = unicode_empty;
1041910421
goto done;
1042010422
}
10421-
if (new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10423+
if (new_size > (PY_SSIZE_T_MAX / rkind)) {
1042210424
PyErr_SetString(PyExc_OverflowError,
1042310425
"replace string is too long");
1042410426
goto error;

0 commit comments

Comments
 (0)