From bda62ba56567b5d278446f6bcd45b7bac53ae29e Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Tue, 25 Jun 2024 15:32:59 +0200 Subject: [PATCH] gh-120155: Fix Coverity issue in parse_string() Add an assertion to make sure that the 'len' variable is at least 1, to make sure that the code '--len' below is safe. Fix the Coverity issue on Python-3.12.2: Error: INTEGER_OVERFLOW (CWE-190): Parser/string_parser.c:236:5: underflow: The decrement operator on the unsigned variable "len" might result in an underflow. Parser/string_parser.c:246:9: overflow: The expression "len -= 2UL" is deemed underflowed because at least one of its arguments has underflowed. Parser/string_parser.c:269:13: overflow_sink: "len", which might have underflowed, is passed to "PyBytes_FromStringAndSize(s, len)". 267| } 268| if (rawmode) { 269|-> return PyBytes_FromStringAndSize(s, len); 270| } 271| return decode_bytes_with_escapes(p, s, len, t); --- Parser/string_parser.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Parser/string_parser.c b/Parser/string_parser.c index bacfd815441110..93ad92b823581e 100644 --- a/Parser/string_parser.c +++ b/Parser/string_parser.c @@ -229,9 +229,14 @@ _PyPegen_parse_string(Parser *p, Token *t) PyErr_BadInternalCall(); return NULL; } + /* Skip the leading quote char. */ s++; len = strlen(s); + // gh-120155: 's' contains at least the trailing quote, + // so the code '--len' below is safe. + assert(len >= 1); + if (len > INT_MAX) { PyErr_SetString(PyExc_OverflowError, "string to parse is too long"); return NULL;