diff --git a/lib/checkers.cpp b/lib/checkers.cpp index fef33042472..e6fed9cde0d 100644 --- a/lib/checkers.cpp +++ b/lib/checkers.cpp @@ -131,6 +131,7 @@ namespace checkers { {"CheckOther::checkInvalidFree",""}, {"CheckOther::checkKnownArgument","style"}, {"CheckOther::checkKnownPointerToBool","style"}, + {"CheckOther::checkMissingForLoopIncrement","warning"}, {"CheckOther::checkMisusedScopedObject","style,c++"}, {"CheckOther::checkModuloOfOne","style"}, {"CheckOther::checkNanInArithmeticExpression","style"}, diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 79697a2e6d7..5db974fe706 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -68,6 +68,7 @@ static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation static const CWE CWE783(783U); // Operator Precedence Logic Error +static const CWE CWE835(835U); // Loop with Unreachable Exit Condition ('Infinite Loop') //---------------------------------------------------------------------------------- // The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value. @@ -4905,6 +4906,205 @@ void CheckOtherImpl::overlappingWriteFunction(const Token *tok, const std::strin reportError(tok, Severity::error, "overlappingWriteFunction", "Overlapping read/write in " + funcname + "() is undefined behavior"); } +//--------------------------------------------------------------------------- +// Detect for-loops that never update their control variable (#5459) +//--------------------------------------------------------------------------- + +static void getStepTokRange(const Token* stepTok, const Token*& stepStart, const Token*& stepEnd) +{ + stepStart = nullptr; + stepEnd = nullptr; + if (!stepTok) + return; + stepStart = previousBeforeAstLeftmostLeaf(stepTok); + if (!stepStart) + stepStart = stepTok; + stepEnd = nextAfterAstRightmostLeaf(stepTok); +} + +static bool stepMayUpdateVar(const Token* stepTok, const Token* loopVarTok, const Settings& settings) +{ + if (!stepTok || !loopVarTok) + return false; + + const Token* stepStart = nullptr; + const Token* stepEnd = nullptr; + getStepTokRange(stepTok, stepStart, stepEnd); + if (!stepEnd) + return true; // cannot determine step range; be conservative + + // Covers ++/--/assignment and updates through calls (inc(&i), std::advance, ...) + if (findExpressionChanged(loopVarTok, stepStart, stepEnd, settings)) + return true; + + // Opaque call/lambda in the step may update the variable in ways we do not see + if (findAstNode(stepTok, [](const Token* tok) { + if (findLambdaEndToken(tok)) + return true; + return tok->isName() && Token::simpleMatch(tok->next(), "(") && !tok->isKeyword(); + })) + return true; + + return false; +} + +static bool hasForLoopExit(const Scope& scope, const Library& library) +{ + for (const Token* tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) { + const Scope* escapeScope = tok->scope(); + if (!escapeScope || !escapeScope->isExecutable()) { + if (escapeScope) + tok = escapeScope->bodyEnd; + continue; + } + if (const Token* lambdaEnd = findLambdaEndToken(tok)) { + tok = lambdaEnd; + continue; + } + if (!tok->isName()) + continue; + // exit/abort/longjmp/[[noreturn]] and similar + if (isEscapeFunction(tok, library)) + return true; + if (!tok->isKeyword()) + continue; + if (Token::Match(tok, "goto|return|throw")) + return true; + if (tok->str() != "break") + continue; + // break only exits this loop if it is not nested in an inner loop/switch + while (escapeScope && escapeScope != &scope) { + if (escapeScope->isLoopScope() || escapeScope->type == ScopeType::eSwitch) + break; + escapeScope = escapeScope->nestedIn; + } + if (escapeScope == &scope) + return true; + } + return false; +} + +static bool isStableLoopBound(const Token* boundTok, + const Token* bodyStart, + const Token* bodyEnd, + const Token* stepTok, + const Settings& settings) +{ + if (!boundTok) + return false; + + // Bound must not contain non-const calls (e.g. get()) or side effects + if (!isConstExpression(boundTok, settings.library)) + return false; + + // Bound must not read volatile data (e.g. i < *p with volatile int *p) + if (findAstNode(boundTok, [](const Token* tok) { + return tok->valueType() && tok->valueType()->volatileness != 0; + })) + return false; + + // Bound must not be modified in the body (e.g. i < n with n-- in the body) + if (findExpressionChanged(boundTok, bodyStart, bodyEnd, settings)) + return false; + + // Bound must not be modified in the step (e.g. for (m = M; i < m; i++)) + if (stepTok) { + const Token* stepStart = nullptr; + const Token* stepEnd = nullptr; + getStepTokRange(stepTok, stepStart, stepEnd); + if (!stepEnd || findExpressionChanged(boundTok, stepStart, stepEnd, settings)) + return false; + } + + return true; +} + +static const Token* findForLoopControlVar(const Token* initTok, const Token* condTok) +{ + if (!initTok || !condTok || !condTok->isComparisonOp()) + return nullptr; + + const Token* initLhs = Token::simpleMatch(initTok, "=") ? initTok->astOperand1() : nullptr; + if (!Token::Match(initLhs, "%var%") || initLhs->varId() == 0) + return nullptr; + + const Variable* var = initLhs->variable(); + if (!var || !var->isLocal() || var->isStatic() || var->isReference() || var->isRValueReference()) + return nullptr; + + auto isAcceptableLoopVar = [](const Token* tok) -> bool { + if (!Token::Match(tok, "%var%") || tok->varId() == 0) + return false; + if (!tok->valueType()) + return true; // incomplete type info; still allow for C / missing VT + return tok->valueType()->isIntegral() || tok->valueType()->type == ValueType::Type::ITERATOR; + }; + + const Token* op1 = condTok->astOperand1(); + const Token* op2 = condTok->astOperand2(); + if (isAcceptableLoopVar(op1) && op1->varId() == initLhs->varId()) + return op1; + if (isAcceptableLoopVar(op2) && op2->varId() == initLhs->varId()) + return op2; + return nullptr; +} + +void CheckOtherImpl::checkMissingForLoopIncrement() +{ + if (!mSettings.severity.isEnabled(Severity::warning)) + return; + + logChecker("CheckOther::checkMissingForLoopIncrement"); // warning + + const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); + for (const Scope& scope : symbolDatabase->scopeList) { + if (scope.type != ScopeType::eFor || !scope.classDef) + continue; + + const Token* forTok = scope.classDef; + const Token* initTok = getInitTok(forTok); + const Token* condTok = getCondTok(forTok); + const Token* stepTok = getStepTok(forTok); + if (!initTok || !condTok) + continue; + + const Token* loopVarTok = findForLoopControlVar(initTok, condTok); + if (!loopVarTok) + continue; + + const nonneg int varId = loopVarTok->varId(); + if (stepMayUpdateVar(stepTok, loopVarTok, mSettings)) + continue; + + if (!astHasVar(condTok, varId)) + continue; + + // The other operand of the comparison must be a stable bound, otherwise the + // loop can terminate without updating the control variable. + const Token* otherBound = (loopVarTok == condTok->astOperand1()) + ? condTok->astOperand2() + : condTok->astOperand1(); + if (!isStableLoopBound(otherBound, scope.bodyStart, scope.bodyEnd, stepTok, mSettings)) + continue; + + if (hasForLoopExit(scope, mSettings.library)) + continue; + + if (findExpressionChanged(loopVarTok, scope.bodyStart, scope.bodyEnd, mSettings)) + continue; + + missingForLoopIncrementError(forTok, loopVarTok->str()); + } +} + +void CheckOtherImpl::missingForLoopIncrementError(const Token *tok, const std::string &varname) +{ + reportError(tok, Severity::warning, "missingForLoopIncrement", + "$symbol:" + varname + "\n" + "The loop variable '$symbol' is not updated in this for-loop, so the loop might never terminate.", + CWE835, Certainty::normal); +} + void CheckOther::runChecks(const Tokenizer &tokenizer, ErrorLogger& errorLogger) { CheckOtherImpl checkOther(&tokenizer, tokenizer.getSettings(), errorLogger); @@ -4956,6 +5156,7 @@ void CheckOther::runChecks(const Tokenizer &tokenizer, ErrorLogger& errorLogger) checkOther.checkModuloOfOne(); checkOther.checkOverlappingWrite(); checkOther.checkUnionZeroInit(); + checkOther.checkMissingForLoopIncrement(); } void CheckOther::getErrorMessages(ErrorLogger& errorLogger, const Settings &settings) const @@ -5041,4 +5242,5 @@ void CheckOther::getErrorMessages(ErrorLogger& errorLogger, const Settings &sett c.funcArgOrderDifferent("function", nullptr, nullptr, nullvec, nullvec); c.checkModuloOfOneError(nullptr); c.unionZeroInitError(nullptr, UnionMember()); + c.missingForLoopIncrementError(nullptr, "i"); } diff --git a/lib/checkother.h b/lib/checkother.h index 61a865e9ab6..91169b535ef 100644 --- a/lib/checkother.h +++ b/lib/checkother.h @@ -77,6 +77,7 @@ class CPPCHECKLIB CheckOther : public Check { // warning "- either division by zero or useless condition\n" "- access of moved or forwarded variable.\n" + "- for-loop that never updates its control variable\n" // performance "- redundant data copying for const variable\n" @@ -267,6 +268,9 @@ class CPPCHECKLIB CheckOtherImpl : public CheckImpl { void overlappingWriteUnion(const Token *tok); void overlappingWriteFunction(const Token *tok, const std::string& funcname); + /** @brief %Check for for-loops that never update their control variable (#5459) */ + void checkMissingForLoopIncrement(); + // Error messages.. void checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, bool result); void checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName); @@ -328,6 +332,7 @@ class CPPCHECKLIB CheckOtherImpl : public CheckImpl { void comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2, bool subtract); void checkModuloOfOneError(const Token *tok); void unionZeroInitError(const Token *tok, const UnionMember& largestMember); + void missingForLoopIncrementError(const Token *tok, const std::string &varname); bool diag(const Token* tok) { return !mRedundantAssignmentDiag.emplace(tok).second; diff --git a/man/checkers/missingForLoopIncrement.md b/man/checkers/missingForLoopIncrement.md new file mode 100644 index 00000000000..95433db306a --- /dev/null +++ b/man/checkers/missingForLoopIncrement.md @@ -0,0 +1,39 @@ +# missingForLoopIncrement + +**Message**: The loop variable 'varname' is not updated in this for-loop, so the loop might never terminate.
+**Category**: Correctness
+**Severity**: Warning
+**Language**: C, C++ + +## Description + +A classic `for` loop's control variable is never advanced in the step clause or the loop body, so the +loop condition may never become false. + +## Motivation + +Forgetting to increment an iterator or index is a common bug that leads to an infinite loop. Compilers +often do not warn about an empty for-loop step when the programmer intended to update the variable in +the body but never did. + +## How to fix + +Before: +```cpp +#include +void f(std::map &theMap) { + for (auto it = theMap.begin(); it != theMap.end();) { + (void)*it; // <- missingForLoopIncrement: 'it' is never updated + } +} +``` + +After: increment in the for-header or in the body. +```cpp +#include +void f(std::map &theMap) { + for (auto it = theMap.begin(); it != theMap.end(); ++it) { + (void)*it; + } +} +``` diff --git a/test/cli/other_test.py b/test/cli/other_test.py index 8e13489e114..61574bb4536 100644 --- a/test/cli/other_test.py +++ b/test/cli/other_test.py @@ -4451,25 +4451,25 @@ def __test_active_checkers(tmp_path, active_cnt, total_cnt, use_misra=False, use def test_active_unusedfunction_only(tmp_path): - __test_active_checkers(tmp_path, 1, 189, use_unusedfunction_only=True) + __test_active_checkers(tmp_path, 1, 190, use_unusedfunction_only=True) def test_active_unusedfunction_only_builddir(tmp_path): checkers_exp = [ 'CheckUnusedFunctions::check' ] - __test_active_checkers(tmp_path, 1, 189, use_unusedfunction_only=True, checkers_exp=checkers_exp) + __test_active_checkers(tmp_path, 1, 190, use_unusedfunction_only=True, checkers_exp=checkers_exp) def test_active_unusedfunction_only_misra(tmp_path): - __test_active_checkers(tmp_path, 1, 389, use_unusedfunction_only=True, use_misra=True) + __test_active_checkers(tmp_path, 1, 390, use_unusedfunction_only=True, use_misra=True) def test_active_unusedfunction_only_misra_builddir(tmp_path): checkers_exp = [ 'CheckUnusedFunctions::check' ] - __test_active_checkers(tmp_path, 1, 389, use_unusedfunction_only=True, use_misra=True, checkers_exp=checkers_exp) + __test_active_checkers(tmp_path, 1, 390, use_unusedfunction_only=True, use_misra=True, checkers_exp=checkers_exp) def test_analyzerinfo(tmp_path): diff --git a/test/testother.cpp b/test/testother.cpp index d6025e9a640..f32cfad2271 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -345,6 +345,8 @@ class TestOther : public TestFixture { TEST_CASE(unionZeroInitStructMember); TEST_CASE(unionZeroInitUnknownType); TEST_CASE(unionZeroInitBitfields); + + TEST_CASE(missingForLoopIncrement); // #5459 } struct CheckOptions @@ -6680,7 +6682,8 @@ class TestOther : public TestFixture { " c ++;\n" " }\n" "}\n"); - ASSERT_EQUALS("[test.cpp:2:31]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead? [constStatement]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:2:31]: (warning, inconclusive) Found suspicious equality comparison. Did you intend to assign a value instead? [constStatement]\n" + "[test.cpp:2:5]: (warning) The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); check("void foo(int c) {\n" " for (; running == 1;) {\n" @@ -8639,7 +8642,8 @@ class TestOther : public TestFixture { " if( i != 0 ) {}\n" " }\n" "}\n"); - ASSERT_EQUALS("[test.cpp:2:17] -> [test.cpp:3:15]: (style) The comparison 'i != 0' is always false. [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:2:17] -> [test.cpp:3:15]: (style) The comparison 'i != 0' is always false. [knownConditionTrueFalse]\n" + "[test.cpp:2:5]: (warning) The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); check("void f() {\n" " for(int i = 0; i < 10;) {\n" @@ -14594,6 +14598,218 @@ class TestOther : public TestFixture { "}\n"); ASSERT_EQUALS("", errout_str()); } + + void missingForLoopIncrement() { // #5459 + // Ticket example: empty step, iterator never updated + check("void f(const std::map& theMap) {\n" + " for (auto it = theMap.begin(); it != theMap.end();) {\n" + " (void)*it;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:3]: (warning) The loop variable 'it' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); + + // Index variable with empty step + check("void use(int);\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " use(i);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3:3]: (warning) The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); + + // Empty body + check("void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:3]: (warning) The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); + + // Step in header — OK + check("void f(const std::map& theMap) {\n" + " for (auto it = theMap.begin(); it != theMap.end(); ++it) {\n" + " (void)*it;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Increment in body — OK + check("void f(const std::map& theMap) {\n" + " for (auto it = theMap.begin(); it != theMap.end();) {\n" + " ++it;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Assignment via erase in body — OK + check("void f(std::map& theMap) {\n" + " for (auto it = theMap.begin(); it != theMap.end();) {\n" + " it = theMap.erase(it);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // += in body — OK + check("void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " i += 1;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // break in body — bail out + check("void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " if (n == 1)\n" + " break;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // return in body — bail out + check("void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " return;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Infinite for(;;) — no identifiable control var + check("void f() {\n" + " for (;;) {\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Range-for — OK + check("void f(const std::vector& v) {\n" + " for (auto x : v) {\n" + " (void)x;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Opaque call that may modify the variable — bail out + check("void g(int& i);\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " g(i);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Nested update in step — OK + check("void f(const std::vector& v) {\n" + " for (auto it = v.begin(); it != v.end(); delete *it++);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Loop var updated on RHS of step assignment — OK + check("void dostuff(int);\n" + "void foo(int num) {\n" + " int a = num;\n" + " for (int b = 0; b < num; a = b++)\n" + " dostuff(a);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Step updates via function call — OK (false positive previously) + check("void inc(int* p) { ++*p; }\n" + "void f(int n) {\n" + " for (int i = 0; i < n; inc(&i)) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Step updates via std::advance — OK + check("#include \n" + "#include \n" + "void f(std::list& l) {\n" + " for (auto it = l.begin(); it != l.end(); std::advance(it, 1)) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Step updates via member taking reference — OK + check("struct S { void step(int& i); };\n" + "void f(S& s, int n) {\n" + " for (int i = 0; i < n; s.step(i)) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Lambda in step that updates the variable — OK + check("void f(int n) {\n" + " for (int i = 0; i < n; ([&]{ i++; })()) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Other operand of condition changes in body — OK + check("void use(int);\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " use(i);\n" + " n--;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Other operand is a non-const function call — OK + check("int get();\n" + "void f() {\n" + " for (int i = 0; i != get();) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Other operand reads volatile — OK + check("void f(const volatile int *p) {\n" + " for (int i = 0; i < *p;) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // Init assigns bound; step updates the other operand — OK + check("void f(int M) {\n" + " int i = 0;\n" + " for (int m = M; i < m; i++) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // noreturn/exit in body — OK + check("#include \n" + "void use(int);\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " use(i);\n" + " exit(1);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // [[noreturn]] in body — OK + check("void use(int);\n" + "[[noreturn]] void fail();\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " use(i);\n" + " fail();\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + // continue alone does not exit the loop — still warn + check("void use(int);\n" + "void f(int n) {\n" + " for (int i = 0; i < n;) {\n" + " if (n > 0)\n" + " continue;\n" + " use(i);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3:3]: (warning) The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); + + // Step updates a different variable, not the control var — still warn + check("void f() {\n" + " int k = 0;\n" + " for (int h = 35; h > 5; k++) {}\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3:3]: (warning) The loop variable 'h' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]\n", errout_str()); + } }; REGISTER_TEST(TestOther)