Skip to content

Commit 64e461b

Browse files
bpo-22207: Add checks for possible integer overflows in unicodeobject.c. (#2623)
Based on patch by Victor Stinner.
1 parent 1180e5a commit 64e461b

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
@@ -5478,13 +5478,12 @@ _PyUnicode_EncodeUTF32(PyObject *str,
54785478
/* four bytes are reserved for each surrogate */
54795479
if (moreunits > 1) {
54805480
Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
5481-
Py_ssize_t morebytes = 4 * (moreunits - 1);
5482-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5481+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
54835482
/* integer overflow */
54845483
PyErr_NoMemory();
54855484
goto error;
54865485
}
5487-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5486+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
54885487
goto error;
54895488
out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
54905489
}
@@ -5830,13 +5829,12 @@ _PyUnicode_EncodeUTF16(PyObject *str,
58305829
/* two bytes are reserved for each surrogate */
58315830
if (moreunits > 1) {
58325831
Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5833-
Py_ssize_t morebytes = 2 * (moreunits - 1);
5834-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5832+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
58355833
/* integer overflow */
58365834
PyErr_NoMemory();
58375835
goto error;
58385836
}
5839-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5837+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
58405838
goto error;
58415839
out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
58425840
}
@@ -6516,6 +6514,10 @@ _PyUnicode_DecodeUnicodeInternal(const char *s,
65166514
1))
65176515
return NULL;
65186516

6517+
if (size < 0) {
6518+
PyErr_BadInternalCall();
6519+
return NULL;
6520+
}
65196521
if (size == 0)
65206522
_Py_RETURN_UNICODE_EMPTY();
65216523

@@ -7303,6 +7305,10 @@ decode_code_page_stateful(int code_page,
73037305
PyErr_SetString(PyExc_ValueError, "invalid code page number");
73047306
return NULL;
73057307
}
7308+
if (size < 0) {
7309+
PyErr_BadInternalCall();
7310+
return NULL;
7311+
}
73067312

73077313
if (consumed)
73087314
*consumed = 0;

0 commit comments

Comments
 (0)