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

Skip to content

Commit 736b801

Browse files
committed
prevent overflow in unicode_repr (closes #22520)
1 parent bbd0a32 commit 736b801

2 files changed

Lines changed: 20 additions & 11 deletions

File tree

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ What's New in Python 3.3.6 release candidate 1?
1010
Core and Builtins
1111
-----------------
1212

13+
- Issue #22520: Fix overflow checking when generating the repr of a unicode
14+
object.
15+
1316
- Issue #22519: Fix overflow checking in PyBytes_Repr.
1417

1518
- Issue #22518: Fix integer overflow issues in latin-1 encoding.

Objects/unicodeobject.c

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12000,28 +12000,34 @@ unicode_repr(PyObject *unicode)
1200012000
ikind = PyUnicode_KIND(unicode);
1200112001
for (i = 0; i < isize; i++) {
1200212002
Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12003+
Py_ssize_t incr = 1;
1200312004
switch (ch) {
12004-
case '\'': squote++; osize++; break;
12005-
case '"': dquote++; osize++; break;
12005+
case '\'': squote++; break;
12006+
case '"': dquote++; break;
1200612007
case '\\': case '\t': case '\r': case '\n':
12007-
osize += 2; break;
12008+
incr = 2;
12009+
break;
1200812010
default:
1200912011
/* Fast-path ASCII */
1201012012
if (ch < ' ' || ch == 0x7f)
12011-
osize += 4; /* \xHH */
12013+
incr = 4; /* \xHH */
1201212014
else if (ch < 0x7f)
12013-
osize++;
12014-
else if (Py_UNICODE_ISPRINTABLE(ch)) {
12015-
osize++;
12015+
;
12016+
else if (Py_UNICODE_ISPRINTABLE(ch))
1201612017
max = ch > max ? ch : max;
12017-
}
1201812018
else if (ch < 0x100)
12019-
osize += 4; /* \xHH */
12019+
incr = 4; /* \xHH */
1202012020
else if (ch < 0x10000)
12021-
osize += 6; /* \uHHHH */
12021+
incr = 6; /* \uHHHH */
1202212022
else
12023-
osize += 10; /* \uHHHHHHHH */
12023+
incr = 10; /* \uHHHHHHHH */
12024+
}
12025+
if (osize > PY_SSIZE_T_MAX - incr) {
12026+
PyErr_SetString(PyExc_OverflowError,
12027+
"string is too long to generate repr");
12028+
return NULL;
1202412029
}
12030+
osize += incr;
1202512031
}
1202612032

1202712033
quote = '\'';

0 commit comments

Comments
 (0)