Repository navigation
Fix #5459 (Detect endless for loops) #9038
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
985cbbe
ea745c0
ac9d650
644096a
f562203
ef2ff1a
d4960e1
a7f0386
ee9270e
bf1435a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,256 @@ 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)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AI review
int limit = 10;
void shrink(void) { limit = 0; }
void f(void) { int *p = &limit; for (int i = 0; i < *p;) { shrink(); } }int limit = 10;
void shrink() { limit = 0; }
void f(const int &lim) { for (int i = 0; i < lim;) { shrink(); } }The same happens with A possible fix: treat a bound that dereferences a pointer, or that is a reference or a non-local variable, as unstable when the body contains a call that isn't const or pure. |
||
| 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 bool isAcceptableForLoopControlVar(const Token* tok) | ||
| { | ||
| if (!Token::Match(tok, "%var%") || tok->varId() == 0) | ||
| return false; | ||
|
|
||
| const Variable* var = tok->variable(); | ||
| if (var && var->isVolatile()) | ||
| return false; | ||
|
|
||
| if (!tok->valueType()) { | ||
| // Incomplete type info: allow only non-class C-like locals (not std::atomic, etc.) | ||
| return !var || !var->isClass(); | ||
| } | ||
|
|
||
| if (tok->valueType()->volatileness != 0) | ||
| return false; | ||
|
|
||
| // Integral/iterator only — rejects class types such as std::atomic | ||
| return tok->valueType()->isIntegral() || tok->valueType()->type == ValueType::Type::ITERATOR; | ||
| } | ||
|
|
||
| static bool addressOrRefTakenBefore(const Variable* var, const Token* before) | ||
| { | ||
| if (!var || !var->nameToken() || !before) | ||
| return false; | ||
|
|
||
| for (const Token* tok = var->nameToken()->next(); tok && tok != before; tok = tok->next()) { | ||
| if (tok->isUnaryOp("&") && tok->astOperand1() && tok->astOperand1()->varId() == var->declarationId()) | ||
| return true; | ||
| // Reference bound to the variable: T& r = var | ||
| if (Token::simpleMatch(tok, "=") && tok->astOperand2() && tok->astOperand2()->varId() == var->declarationId()) { | ||
| const Token* lhs = tok->astOperand1(); | ||
| if (lhs && lhs->variable() && lhs->variable()->isReference()) | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| static bool loopBodyHasCall(const Scope& scope) | ||
| { | ||
| for (const Token* tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) { | ||
| if (const Token* lambdaEnd = findLambdaEndToken(tok)) { | ||
| tok = lambdaEnd; | ||
| continue; | ||
| } | ||
| if (tok->isName() && Token::simpleMatch(tok->next(), "(") && !tok->isKeyword()) | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| 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; | ||
| if (var->isVolatile()) | ||
| return nullptr; | ||
|
|
||
| const Token* op1 = condTok->astOperand1(); | ||
| const Token* op2 = condTok->astOperand2(); | ||
| if (isAcceptableForLoopControlVar(op1) && op1->varId() == initLhs->varId()) | ||
| return op1; | ||
| if (isAcceptableForLoopControlVar(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)) | ||
|
willgarvin marked this conversation as resolved.
Resolved
|
||
| 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; | ||
|
|
||
| // Address/reference may have escaped before the loop; a call in the body | ||
| // might update the variable through that alias. | ||
| if (addressOrRefTakenBefore(loopVarTok->variable(), forTok) && loopBodyHasCall(scope)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AI review This bail-out only applies when the body also contains a call. If the variable is changed in the body directly through a reference that was bound before the loop, the check still warns: void f(int n) {
int i;
int &r = i;
for (i = 0; i < n;) { r++; }
}Output: Possible fixes:
|
||
| 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 +5207,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 +5293,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"); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| # missingForLoopIncrement | ||
|
|
||
| **Message**: The loop variable 'varname' is not updated in this for-loop, so the loop might never terminate.<br/> | ||
| **Category**: Correctness<br/> | ||
| **Severity**: Warning<br/> | ||
| **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 <map> | ||
| void f(std::map<int, int> &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 <map> | ||
| void f(std::map<int, int> &theMap) { | ||
| for (auto it = theMap.begin(); it != theMap.end(); ++it) { | ||
| (void)*it; | ||
| } | ||
| } | ||
| ``` |
Uh oh!
There was an error while loading. Please reload this page.