Skip to content

Commit 44eb51e

Browse files
[3.5] bpo-22207: Add checks for possible integer overflows in unicodeobject.c. (GH-2623) (#2659)
Based on patch by Victor Stinner. (cherry picked from commit 64e461b)
1 parent 7527c32 commit 44eb51e

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

Objects/unicodeobject.c

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5209,13 +5209,12 @@ _PyUnicode_EncodeUTF32(PyObject *str,
52095209
/* four bytes are reserved for each surrogate */
52105210
if (moreunits > 1) {
52115211
Py_ssize_t outpos = out - (PY_UINT32_T*) PyBytes_AS_STRING(v);
5212-
Py_ssize_t morebytes = 4 * (moreunits - 1);
5213-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5212+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
52145213
/* integer overflow */
52155214
PyErr_NoMemory();
52165215
goto error;
52175216
}
5218-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5217+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
52195218
goto error;
52205219
out = (PY_UINT32_T*) PyBytes_AS_STRING(v) + outpos;
52215220
}
@@ -5552,13 +5551,12 @@ _PyUnicode_EncodeUTF16(PyObject *str,
55525551
/* two bytes are reserved for each surrogate */
55535552
if (moreunits > 1) {
55545553
Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5555-
Py_ssize_t morebytes = 2 * (moreunits - 1);
5556-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5554+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
55575555
/* integer overflow */
55585556
PyErr_NoMemory();
55595557
goto error;
55605558
}
5561-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5559+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
55625560
goto error;
55635561
out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
55645562
}
@@ -6250,6 +6248,10 @@ _PyUnicode_DecodeUnicodeInternal(const char *s,
62506248
1))
62516249
return NULL;
62526250

6251+
if (size < 0) {
6252+
PyErr_BadInternalCall();
6253+
return NULL;
6254+
}
62536255
if (size == 0)
62546256
_Py_RETURN_UNICODE_EMPTY();
62556257

@@ -7052,6 +7054,10 @@ decode_code_page_stateful(int code_page,
70527054
PyErr_SetString(PyExc_ValueError, "invalid code page number");
70537055
return NULL;
70547056
}
7057+
if (size < 0) {
7058+
PyErr_BadInternalCall();
7059+
return NULL;
7060+
}
70557061

70567062
if (consumed)
70577063
*consumed = 0;

0 commit comments

Comments
 (0)