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<qsizetype>::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 <thiago.macieira@intel.com>
(cherry picked from commit 72422d7d1b2a1f71415b5662724f88f490eadaf8)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Marc Mutz 2023-12-07 09:22:58 +01:00 committed by Qt Cherry-pick Bot
parent c3c171c234
commit 3ff26d77eb

View File

@ -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));