Skip to content

Commit 82a9075

Browse files
[3.6] bpo-22207: Add checks for possible integer overflows in unicodeobject.c. (GH-2623) (#2658)
Based on patch by Victor Stinner. (cherry picked from commit 64e461b)
1 parent ecfe4f6 commit 82a9075

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
@@ -5513,13 +5513,12 @@ _PyUnicode_EncodeUTF32(PyObject *str,
55135513
/* four bytes are reserved for each surrogate */
55145514
if (moreunits > 1) {
55155515
Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
5516-
Py_ssize_t morebytes = 4 * (moreunits - 1);
5517-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5516+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
55185517
/* integer overflow */
55195518
PyErr_NoMemory();
55205519
goto error;
55215520
}
5522-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5521+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * (moreunits - 1)) < 0)
55235522
goto error;
55245523
out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
55255524
}
@@ -5865,13 +5864,12 @@ _PyUnicode_EncodeUTF16(PyObject *str,
58655864
/* two bytes are reserved for each surrogate */
58665865
if (moreunits > 1) {
58675866
Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
5868-
Py_ssize_t morebytes = 2 * (moreunits - 1);
5869-
if (PyBytes_GET_SIZE(v) > PY_SSIZE_T_MAX - morebytes) {
5867+
if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
58705868
/* integer overflow */
58715869
PyErr_NoMemory();
58725870
goto error;
58735871
}
5874-
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + morebytes) < 0)
5872+
if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * (moreunits - 1)) < 0)
58755873
goto error;
58765874
out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
58775875
}
@@ -6551,6 +6549,10 @@ _PyUnicode_DecodeUnicodeInternal(const char *s,
65516549
1))
65526550
return NULL;
65536551

6552+
if (size < 0) {
6553+
PyErr_BadInternalCall();
6554+
return NULL;
6555+
}
65546556
if (size == 0)
65556557
_Py_RETURN_UNICODE_EMPTY();
65566558

@@ -7352,6 +7354,10 @@ decode_code_page_stateful(int code_page,
73527354
PyErr_SetString(PyExc_ValueError, "invalid code page number");
73537355
return NULL;
73547356
}
7357+
if (size < 0) {
7358+
PyErr_BadInternalCall();
7359+
return NULL;
7360+
}
73557361

73567362
if (consumed)
73577363
*consumed = 0;

0 commit comments

Comments
 (0)