Skip to content

Commit cbc7c2c

Browse files
bpo-35552: Fix reading past the end in PyUnicode_FromFormat() and PyBytes_FromFormat(). (GH-11276)
Format characters "%s" and "%V" in PyUnicode_FromFormat() and "%s" in PyBytes_FromFormat() no longer read memory past the limit if precision is specified. (cherry picked from commit d586ccb) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent d39c192 commit cbc7c2c

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Format characters ``%s`` and ``%V`` in :c:func:`PyUnicode_FromFormat` and
2+
``%s`` in :c:func:`PyBytes_FromFormat` no longer read memory past the
3+
limit if *precision* is specified.

Objects/bytesobject.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -311,9 +311,15 @@ PyBytes_FromFormatV(const char *format, va_list vargs)
311311
Py_ssize_t i;
312312

313313
p = va_arg(vargs, const char*);
314-
i = strlen(p);
315-
if (prec > 0 && i > prec)
316-
i = prec;
314+
if (prec <= 0) {
315+
i = strlen(p);
316+
}
317+
else {
318+
i = 0;
319+
while (i < prec && p[i]) {
320+
i++;
321+
}
322+
}
317323
s = _PyBytesWriter_WriteBytes(&writer, s, p, i);
318324
if (s == NULL)
319325
goto error;

Objects/unicodeobject.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2579,9 +2579,15 @@ unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
25792579
PyObject *unicode;
25802580
int res;
25812581

2582-
length = strlen(str);
2583-
if (precision != -1)
2584-
length = Py_MIN(length, precision);
2582+
if (precision == -1) {
2583+
length = strlen(str);
2584+
}
2585+
else {
2586+
length = 0;
2587+
while (length < precision && str[length]) {
2588+
length++;
2589+
}
2590+
}
25852591
unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
25862592
if (unicode == NULL)
25872593
return -1;

0 commit comments

Comments
 (0)