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
d586ccb04f79863c819b212ec5b9d873964078e4)
Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
--- /dev/null
+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.
Py_ssize_t i;
p = va_arg(vargs, const char*);
- i = strlen(p);
- if (prec > 0 && i > prec)
- i = prec;
+ if (prec <= 0) {
+ i = strlen(p);
+ }
+ else {
+ i = 0;
+ while (i < prec && p[i]) {
+ i++;
+ }
+ }
s = _PyBytesWriter_WriteBytes(&writer, s, p, i);
if (s == NULL)
goto error;
PyObject *unicode;
int res;
- length = strlen(str);
- if (precision != -1)
- length = Py_MIN(length, precision);
+ if (precision == -1) {
+ length = strlen(str);
+ }
+ else {
+ length = 0;
+ while (length < precision && str[length]) {
+ length++;
+ }
+ }
unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
if (unicode == NULL)
return -1;