Skip to content

Commit 985cbbe

Browse files
committed
Fix #5459 Detect Endless For Loops
1 parent 275e673 commit 985cbbe

5 files changed

Lines changed: 275 additions & 0 deletions

File tree

‎lib/checkers.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ namespace checkers {
131131
{"CheckOther::checkInvalidFree",""},
132132
{"CheckOther::checkKnownArgument","style"},
133133
{"CheckOther::checkKnownPointerToBool","style"},
134+
{"CheckOther::checkMissingForLoopIncrement","warning"},
134135
{"CheckOther::checkMisusedScopedObject","style,c++"},
135136
{"CheckOther::checkModuloOfOne","style"},
136137
{"CheckOther::checkNanInArithmeticExpression","style"},

‎lib/checkother.cpp‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
6868
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
6969
static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation
7070
static const CWE CWE783(783U); // Operator Precedence Logic Error
71+
static const CWE CWE835(835U); // Loop with Unreachable Exit Condition ('Infinite Loop')
7172

7273
//----------------------------------------------------------------------------------
7374
// The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value.
@@ -4905,6 +4906,132 @@ void CheckOtherImpl::overlappingWriteFunction(const Token *tok, const std::strin
49054906
reportError(tok, Severity::error, "overlappingWriteFunction", "Overlapping read/write in " + funcname + "() is undefined behavior");
49064907
}
49074908

4909+
//---------------------------------------------------------------------------
4910+
// Detect for-loops that never update their control variable (#5459)
4911+
//---------------------------------------------------------------------------
4912+
4913+
static bool stepUpdatesVar(const Token* stepTok, nonneg int varId)
4914+
{
4915+
if (!stepTok || varId == 0)
4916+
return false;
4917+
if (stepTok->str() == ",")
4918+
return stepUpdatesVar(stepTok->astOperand1(), varId) || stepUpdatesVar(stepTok->astOperand2(), varId);
4919+
if (stepTok->isIncDecOp() && stepTok->astOperand1() && stepTok->astOperand1()->varId() == varId)
4920+
return true;
4921+
if (stepTok->isAssignmentOp() && stepTok->astOperand1() && stepTok->astOperand1()->varId() == varId) // TODO: WILL THIS RETURN TRUE IF STEP IS SOMETHING LIKE: i=i
4922+
return true;
4923+
return false;
4924+
}
4925+
4926+
static bool hasForLoopExit(const Scope& scope)
4927+
{
4928+
for (const Token* tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) {
4929+
const Scope* escapeScope = tok->scope();
4930+
if (!escapeScope || !escapeScope->isExecutable()) {
4931+
if (escapeScope)
4932+
tok = escapeScope->bodyEnd;
4933+
continue;
4934+
}
4935+
if (const Token* lambdaEnd = findLambdaEndToken(tok)) {
4936+
tok = lambdaEnd;
4937+
continue;
4938+
}
4939+
if (!tok->isName() || !tok->isKeyword())
4940+
continue;
4941+
if (Token::Match(tok, "goto|return|throw")) //TODO: WILL THIS RETURN TRUE IF GOTO STAYS WITHIN THE LOOP
4942+
return true;
4943+
if (tok->str() != "break")
4944+
continue;
4945+
// break only exits this loop if it is not nested in an inner loop/switch
4946+
while (escapeScope && escapeScope != &scope) {
4947+
if (escapeScope->isLoopScope() || escapeScope->type == ScopeType::eSwitch)
4948+
break;
4949+
escapeScope = escapeScope->nestedIn;
4950+
}
4951+
if (escapeScope == &scope)
4952+
return true;
4953+
}
4954+
return false;
4955+
}
4956+
4957+
static const Token* findForLoopControlVar(const Token* initTok, const Token* condTok)
4958+
{
4959+
if (!initTok || !condTok || !condTok->isComparisonOp())
4960+
return nullptr;
4961+
4962+
const Token* initLhs = Token::simpleMatch(initTok, "=") ? initTok->astOperand1() : nullptr;
4963+
if (!Token::Match(initLhs, "%var%") || initLhs->varId() == 0) //TODO: WILL THIS BE NULLPTR DEFERENCE IF initLhs IS SET TO NULLPTR ON LINE 4962??
4964+
return nullptr;
4965+
4966+
const Variable* var = initLhs->variable();
4967+
if (!var || !var->isLocal() || var->isStatic() || var->isReference() || var->isRValueReference())
4968+
return nullptr;
4969+
4970+
auto isAcceptableLoopVar = [](const Token* tok) -> bool {
4971+
if (!Token::Match(tok, "%var%") || tok->varId() == 0)
4972+
return false;
4973+
if (!tok->valueType())
4974+
return true; // incomplete type info; still allow for C / missing VT
4975+
return tok->valueType()->isIntegral() || tok->valueType()->type == ValueType::Type::ITERATOR;
4976+
};
4977+
4978+
const Token* op1 = condTok->astOperand1();
4979+
const Token* op2 = condTok->astOperand2();
4980+
if (isAcceptableLoopVar(op1) && op1->varId() == initLhs->varId())
4981+
return op1;
4982+
if (isAcceptableLoopVar(op2) && op2->varId() == initLhs->varId())
4983+
return op2;
4984+
return nullptr;
4985+
}
4986+
4987+
void CheckOtherImpl::checkMissingForLoopIncrement()
4988+
{
4989+
if (!mSettings.severity.isEnabled(Severity::warning))
4990+
return;
4991+
4992+
logChecker("CheckOther::checkMissingForLoopIncrement"); // warning
4993+
4994+
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
4995+
for (const Scope& scope : symbolDatabase->scopeList) {
4996+
if (scope.type != ScopeType::eFor || !scope.classDef)
4997+
continue;
4998+
4999+
const Token* forTok = scope.classDef;
5000+
const Token* initTok = getInitTok(forTok);
5001+
const Token* condTok = getCondTok(forTok);
5002+
const Token* stepTok = getStepTok(forTok);
5003+
if (!initTok || !condTok)
5004+
continue;
5005+
5006+
const Token* loopVarTok = findForLoopControlVar(initTok, condTok);
5007+
if (!loopVarTok)
5008+
continue;
5009+
5010+
const nonneg int varId = loopVarTok->varId();
5011+
if (stepUpdatesVar(stepTok, varId))
5012+
continue;
5013+
5014+
if (!astHasVar(condTok, varId))
5015+
continue;
5016+
5017+
if (hasForLoopExit(scope))
5018+
continue;
5019+
5020+
if (findExpressionChanged(loopVarTok, scope.bodyStart, scope.bodyEnd, mSettings))
5021+
continue;
5022+
5023+
missingForLoopIncrementError(forTok, loopVarTok->str());
5024+
}
5025+
}
5026+
5027+
void CheckOtherImpl::missingForLoopIncrementError(const Token *tok, const std::string &varname)
5028+
{
5029+
reportError(tok, Severity::warning, "missingForLoopIncrement",
5030+
"$symbol:" + varname + "\n"
5031+
"The loop variable '$symbol' is not updated in this for-loop, so the loop might never terminate.",
5032+
CWE835, Certainty::normal);
5033+
}
5034+
49085035
void CheckOther::runChecks(const Tokenizer &tokenizer, ErrorLogger& errorLogger)
49095036
{
49105037
CheckOtherImpl checkOther(&tokenizer, tokenizer.getSettings(), errorLogger);
@@ -4956,6 +5083,7 @@ void CheckOther::runChecks(const Tokenizer &tokenizer, ErrorLogger& errorLogger)
49565083
checkOther.checkModuloOfOne();
49575084
checkOther.checkOverlappingWrite();
49585085
checkOther.checkUnionZeroInit();
5086+
checkOther.checkMissingForLoopIncrement();
49595087
}
49605088

49615089
void CheckOther::getErrorMessages(ErrorLogger& errorLogger, const Settings &settings) const
@@ -5041,4 +5169,5 @@ void CheckOther::getErrorMessages(ErrorLogger& errorLogger, const Settings &sett
50415169
c.funcArgOrderDifferent("function", nullptr, nullptr, nullvec, nullvec);
50425170
c.checkModuloOfOneError(nullptr);
50435171
c.unionZeroInitError(nullptr, UnionMember());
5172+
c.missingForLoopIncrementError(nullptr, "i");
50445173
}

‎lib/checkother.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ class CPPCHECKLIB CheckOther : public Check {
7777
// warning
7878
"- either division by zero or useless condition\n"
7979
"- access of moved or forwarded variable.\n"
80+
"- for-loop that never updates its control variable\n"
8081

8182
// performance
8283
"- redundant data copying for const variable\n"
@@ -267,6 +268,9 @@ class CPPCHECKLIB CheckOtherImpl : public CheckImpl {
267268
void overlappingWriteUnion(const Token *tok);
268269
void overlappingWriteFunction(const Token *tok, const std::string& funcname);
269270

271+
/** @brief %Check for for-loops that never update their control variable (#5459) */
272+
void checkMissingForLoopIncrement();
273+
270274
// Error messages..
271275
void checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, bool result);
272276
void checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName);
@@ -328,6 +332,7 @@ class CPPCHECKLIB CheckOtherImpl : public CheckImpl {
328332
void comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2, bool subtract);
329333
void checkModuloOfOneError(const Token *tok);
330334
void unionZeroInitError(const Token *tok, const UnionMember& largestMember);
335+
void missingForLoopIncrementError(const Token *tok, const std::string &varname);
331336

332337
bool diag(const Token* tok) {
333338
return !mRedundantAssignmentDiag.emplace(tok).second;
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# missingForLoopIncrement
2+
3+
**Message**: The loop variable 'varname' is not updated in this for-loop, so the loop might never terminate.<br/>
4+
**Category**: Correctness<br/>
5+
**Severity**: Warning<br/>
6+
**Language**: C, C++
7+
8+
## Description
9+
10+
A classic `for` loop's control variable is never advanced in the step clause or the loop body, so the
11+
loop condition may never become false.
12+
13+
## Motivation
14+
15+
Forgetting to increment an iterator or index is a common bug that leads to an infinite loop. Compilers
16+
often do not warn about an empty for-loop step when the programmer intended to update the variable in
17+
the body but never did.
18+
19+
## How to fix
20+
21+
Before:
22+
```cpp
23+
#include <map>
24+
void f(std::map<int, int> &theMap) {
25+
for (auto it = theMap.begin(); it != theMap.end();) {
26+
(void)*it; // <- missingForLoopIncrement: 'it' is never updated
27+
}
28+
}
29+
```
30+
31+
After: increment in the for-header or in the body.
32+
```cpp
33+
#include <map>
34+
void f(std::map<int, int> &theMap) {
35+
for (auto it = theMap.begin(); it != theMap.end(); ++it) {
36+
(void)*it;
37+
}
38+
}
39+
```

‎test/testother.cpp‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,8 @@ class TestOther : public TestFixture {
345345
TEST_CASE(unionZeroInitStructMember);
346346
TEST_CASE(unionZeroInitUnknownType);
347347
TEST_CASE(unionZeroInitBitfields);
348+
349+
TEST_CASE(missingForLoopIncrement); // #5459
348350
}
349351

350352
struct CheckOptions
@@ -14594,6 +14596,105 @@ class TestOther : public TestFixture {
1459414596
"}\n");
1459514597
ASSERT_EQUALS("", errout_str());
1459614598
}
14599+
14600+
void missingForLoopIncrement() { // #5459
14601+
// Ticket example: empty step, iterator never updated
14602+
check("void f(const std::map<int,int>& theMap) {\n"
14603+
" for (auto it = theMap.begin(); it != theMap.end();) {\n"
14604+
" (void)*it;\n"
14605+
" }\n"
14606+
"}\n");
14607+
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());
14608+
14609+
// Index variable with empty step
14610+
check("void use(int);\n"
14611+
"void f(int n) {\n"
14612+
" for (int i = 0; i < n;) {\n"
14613+
" use(i);\n"
14614+
" }\n"
14615+
"}\n");
14616+
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());
14617+
14618+
// Empty body
14619+
check("void f(int n) {\n"
14620+
" for (int i = 0; i < n;) {\n"
14621+
" }\n"
14622+
"}\n");
14623+
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());
14624+
14625+
// Step in header — OK
14626+
check("void f(const std::map<int,int>& theMap) {\n"
14627+
" for (auto it = theMap.begin(); it != theMap.end(); ++it) {\n"
14628+
" (void)*it;\n"
14629+
" }\n"
14630+
"}\n");
14631+
ASSERT_EQUALS("", errout_str());
14632+
14633+
// Increment in body — OK
14634+
check("void f(const std::map<int,int>& theMap) {\n"
14635+
" for (auto it = theMap.begin(); it != theMap.end();) {\n"
14636+
" ++it;\n"
14637+
" }\n"
14638+
"}\n");
14639+
ASSERT_EQUALS("", errout_str());
14640+
14641+
// Assignment via erase in body — OK
14642+
check("void f(std::map<int,int>& theMap) {\n"
14643+
" for (auto it = theMap.begin(); it != theMap.end();) {\n"
14644+
" it = theMap.erase(it);\n"
14645+
" }\n"
14646+
"}\n");
14647+
ASSERT_EQUALS("", errout_str());
14648+
14649+
// += in body — OK
14650+
check("void f(int n) {\n"
14651+
" for (int i = 0; i < n;) {\n"
14652+
" i += 1;\n"
14653+
" }\n"
14654+
"}\n");
14655+
ASSERT_EQUALS("", errout_str());
14656+
14657+
// break in body — bail out
14658+
check("void f(int n) {\n"
14659+
" for (int i = 0; i < n;) {\n"
14660+
" if (n == 1)\n"
14661+
" break;\n"
14662+
" }\n"
14663+
"}\n");
14664+
ASSERT_EQUALS("", errout_str());
14665+
14666+
// return in body — bail out
14667+
check("void f(int n) {\n"
14668+
" for (int i = 0; i < n;) {\n"
14669+
" return;\n"
14670+
" }\n"
14671+
"}\n");
14672+
ASSERT_EQUALS("", errout_str());
14673+
14674+
// Infinite for(;;) — no identifiable control var
14675+
check("void f() {\n"
14676+
" for (;;) {\n"
14677+
" }\n"
14678+
"}\n");
14679+
ASSERT_EQUALS("", errout_str());
14680+
14681+
// Range-for — OK
14682+
check("void f(const std::vector<int>& v) {\n"
14683+
" for (auto x : v) {\n"
14684+
" (void)x;\n"
14685+
" }\n"
14686+
"}\n");
14687+
ASSERT_EQUALS("", errout_str());
14688+
14689+
// Opaque call that may modify the variable — bail out
14690+
check("void g(int& i);\n"
14691+
"void f(int n) {\n"
14692+
" for (int i = 0; i < n;) {\n"
14693+
" g(i);\n"
14694+
" }\n"
14695+
"}\n");
14696+
ASSERT_EQUALS("", errout_str());
14697+
}
1459714698
};
1459814699

1459914700
REGISTER_TEST(TestOther)

0 commit comments

Comments
 (0)