From 3ff26d77eb432503cd125cba92b8ba150ef2a793 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Thu, 7 Dec 2023 09:22:58 +0100 Subject: [PATCH] QString::indexOf(): fix UB (signed integer overflow) in negative from handling The `from` value is not constrained, so the code must be able to handle all values, incl. `Min := numeric_limits::min()`. But the result of negating `Min` is not representable in qsizetype, so it's UB to try. Fix by multiplying both sides by -1 (which flips the relational operator). This works because the size() of a string is always non-negative, and the negation of all such values is representable in the same type. Add a comment to avoid a "fix back". Amends f9b867216ba2728ff993020599f5062e2f023de1. Pick-to: 6.5 Change-Id: I10d2e400b86f07a6a6c0a61080a27f41a16b3517 Reviewed-by: Thiago Macieira (cherry picked from commit 72422d7d1b2a1f71415b5662724f88f490eadaf8) Reviewed-by: Qt Cherry-pick Bot --- src/corelib/text/qstring.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index d2af9ff2abf..1f7f1f6d11f 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -134,7 +134,7 @@ static inline bool foldAndCompare(const T a, const T b) */ static inline qsizetype qFindChar(QStringView str, QChar ch, qsizetype from, Qt::CaseSensitivity cs) noexcept { - if (-from > str.size()) + if (from < -str.size()) // from < 0 && abs(from) > str.size(), avoiding overflow return -1; if (from < 0) from = qMax(from + str.size(), qsizetype(0));