Commit d586ccb0 authored by Serhiy Storchaka's avatar Serhiy Storchaka Committed by GitHub

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.
parent f1ec3cef
Format characters ``%s`` and ``%V`` in :c:func:`PyUnicode_FromFormat` and
``%s`` in :c:func:`PyBytes_FromFormat` no longer read memory past the
limit if *precision* is specified.
...@@ -312,9 +312,15 @@ PyBytes_FromFormatV(const char *format, va_list vargs) ...@@ -312,9 +312,15 @@ PyBytes_FromFormatV(const char *format, va_list vargs)
Py_ssize_t i; Py_ssize_t i;
p = va_arg(vargs, const char*); p = va_arg(vargs, const char*);
i = strlen(p); if (prec <= 0) {
if (prec > 0 && i > prec) i = strlen(p);
i = prec; }
else {
i = 0;
while (i < prec && p[i]) {
i++;
}
}
s = _PyBytesWriter_WriteBytes(&writer, s, p, i); s = _PyBytesWriter_WriteBytes(&writer, s, p, i);
if (s == NULL) if (s == NULL)
goto error; goto error;
......
...@@ -2578,9 +2578,15 @@ unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str, ...@@ -2578,9 +2578,15 @@ unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
PyObject *unicode; PyObject *unicode;
int res; int res;
length = strlen(str); if (precision == -1) {
if (precision != -1) length = strlen(str);
length = Py_MIN(length, precision); }
else {
length = 0;
while (length < precision && str[length]) {
length++;
}
}
unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL); unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
if (unicode == NULL) if (unicode == NULL)
return -1; return -1;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment