Skip to content

Commit bd02ca5

Browse files
pfultz2danmar
authored andcommitted
Fix issue 9207: Not detected 'always true' and unreachable code
1 parent 2df7ce2 commit bd02ca5

8 files changed

Lines changed: 228 additions & 38 deletions

File tree

‎lib/astutils.cpp‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,23 @@ bool isUniqueExpression(const Token* tok)
788788
return isUniqueExpression(tok->astOperand2());
789789
}
790790

791-
bool isReturnScope(const Token * const endToken)
791+
static bool isEscaped(const Token* tok, bool functionsScope)
792+
{
793+
if (functionsScope)
794+
return Token::simpleMatch(tok, "throw");
795+
else
796+
return Token::Match(tok, "return|throw");
797+
}
798+
799+
static bool isEscapedOrJump(const Token* tok, bool functionsScope)
800+
{
801+
if (functionsScope)
802+
return Token::simpleMatch(tok, "throw");
803+
else
804+
return Token::Match(tok, "return|goto|throw|continue|break");
805+
}
806+
807+
bool isReturnScope(const Token * const endToken, const Settings * settings, bool functionScope)
792808
{
793809
if (!endToken || endToken->str() != "}")
794810
return false;
@@ -801,28 +817,39 @@ bool isReturnScope(const Token * const endToken)
801817

802818
if (Token::simpleMatch(prev, "}")) {
803819
if (Token::simpleMatch(prev->link()->tokAt(-2), "} else {"))
804-
return isReturnScope(prev) && isReturnScope(prev->link()->tokAt(-2));
820+
return isReturnScope(prev, settings, functionScope) && isReturnScope(prev->link()->tokAt(-2), settings, functionScope);
805821
if (Token::simpleMatch(prev->link()->previous(), ") {") &&
806822
Token::simpleMatch(prev->link()->linkAt(-1)->previous(), "switch (") &&
807823
!Token::findsimplematch(prev->link(), "break", prev)) {
808824
return true;
809825
}
810-
if (Token::Match(prev->link()->astTop(), "return|throw"))
826+
if (isEscaped(prev->link()->astTop(), functionScope))
811827
return true;
812828
if (Token::Match(prev->link()->previous(), "[;{}] {"))
813-
return isReturnScope(prev);
829+
return isReturnScope(prev, settings, functionScope);
814830
} else if (Token::simpleMatch(prev, ";")) {
815-
// noreturn function
816-
if (Token::simpleMatch(prev->previous(), ") ;") && Token::Match(prev->linkAt(-1)->tokAt(-2), "[;{}] %name% ("))
817-
return true;
831+
if (Token::simpleMatch(prev->previous(), ") ;") && Token::Match(prev->linkAt(-1)->tokAt(-2), "[;{}] %name% (")) {
832+
const Token * ftok = prev->linkAt(-1)->previous();
833+
const Function * function = ftok->function();
834+
if (function) {
835+
if (function->isEscapeFunction())
836+
return true;
837+
if (function->isAttributeNoreturn())
838+
return true;
839+
} else if (settings) {
840+
if (settings->library.isnoreturn(ftok))
841+
return true;
842+
}
843+
return false;
844+
}
818845
if (Token::simpleMatch(prev->previous(), ") ;") && prev->previous()->link() &&
819-
Token::Match(prev->previous()->link()->astTop(), "return|throw"))
846+
isEscaped(prev->previous()->link()->astTop(), functionScope))
820847
return true;
821-
if (Token::Match(prev->previous()->astTop(), "return|throw"))
848+
if (isEscaped(prev->previous()->astTop(), functionScope))
822849
return true;
823850
// return/goto statement
824851
prev = prev->previous();
825-
while (prev && !Token::Match(prev, ";|{|}|return|goto|throw|continue|break"))
852+
while (prev && !Token::Match(prev, ";|{|}") && !isEscapedOrJump(prev, functionScope))
826853
prev = prev->previous();
827854
return prev && prev->isName();
828855
}

‎lib/astutils.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ bool isWithoutSideEffects(bool cpp, const Token* tok);
109109
bool isUniqueExpression(const Token* tok);
110110

111111
/** Is scope a return scope (scope will unconditionally return) */
112-
bool isReturnScope(const Token *endToken);
112+
bool isReturnScope(const Token *endToken, const Settings * settings = nullptr, bool functionScope=false);
113113

114114
/** Is variable changed by function call?
115115
* In case the answer of the question is inconclusive, e.g. because the function declaration is not known

‎lib/symboldatabase.cpp‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ SymbolDatabase::SymbolDatabase(const Tokenizer *tokenizer, const Settings *setti
6363
createSymbolDatabaseSetFunctionPointers(true);
6464
createSymbolDatabaseSetTypePointers();
6565
createSymbolDatabaseEnums();
66+
createSymbolDatabaseEscapeFunctions();
6667
createSymbolDatabaseIncompleteVars();
6768
}
6869

@@ -1380,6 +1381,18 @@ void SymbolDatabase::createSymbolDatabaseIncompleteVars()
13801381
}
13811382
}
13821383

1384+
void SymbolDatabase::createSymbolDatabaseEscapeFunctions()
1385+
{
1386+
for (Scope & scope : scopeList) {
1387+
if (scope.type != Scope::eFunction)
1388+
continue;
1389+
Function * function = scope.function;
1390+
if (!function)
1391+
continue;
1392+
function->isEscapeFunction(isReturnScope(scope.bodyEnd, mSettings, true));
1393+
}
1394+
}
1395+
13831396
void SymbolDatabase::setArrayDimensionsUsingValueFlow()
13841397
{
13851398
// set all unknown array dimensions

‎lib/symboldatabase.h‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,7 @@ class CPPCHECKLIB Function {
686686
fIsVariadic = (1 << 19), ///< @brief is variadic
687687
fIsVolatile = (1 << 20), ///< @brief is volatile
688688
fHasTrailingReturnType = (1 << 21), ///< @brief has trailing return type
689+
fIsEscapeFunction = (1 << 22), ///< @brief Function throws or exits
689690
};
690691

691692
/**
@@ -834,11 +835,16 @@ class CPPCHECKLIB Function {
834835
bool hasTrailingReturnType() const {
835836
return getFlag(fHasTrailingReturnType);
836837
}
837-
838838
void hasBody(bool state) {
839839
setFlag(fHasBody, state);
840840
}
841841

842+
bool isEscapeFunction() const {
843+
return getFlag(fIsEscapeFunction);
844+
}
845+
void isEscapeFunction(bool state) {
846+
setFlag(fIsEscapeFunction, state);
847+
}
842848
bool isSafe(const Settings *settings) const;
843849

844850
const Token *tokenDef; ///< function name token in class definition
@@ -1269,6 +1275,7 @@ class CPPCHECKLIB SymbolDatabase {
12691275
void createSymbolDatabaseSetVariablePointers();
12701276
void createSymbolDatabaseSetTypePointers();
12711277
void createSymbolDatabaseEnums();
1278+
void createSymbolDatabaseEscapeFunctions();
12721279
void createSymbolDatabaseIncompleteVars();
12731280

12741281
void addClassFunction(Scope **scope, const Token **tok, const Token *argStart);

‎lib/valueflow.cpp‎

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1998,7 +1998,7 @@ static bool valueFlowForward(Token * const startToken,
19981998
++indentlevel;
19991999
else if (indentlevel >= 0 && tok2->str() == "}") {
20002000
--indentlevel;
2001-
if (indentlevel <= 0 && isReturnScope(tok2) && Token::Match(tok2->link()->previous(), "else|) {")) {
2001+
if (indentlevel <= 0 && isReturnScope(tok2, settings) && Token::Match(tok2->link()->previous(), "else|) {")) {
20022002
const Token *condition = tok2->link();
20032003
const bool iselse = Token::simpleMatch(condition->tokAt(-2), "} else {");
20042004
if (iselse)
@@ -2039,7 +2039,7 @@ static bool valueFlowForward(Token * const startToken,
20392039
return true;
20402040
} else if (indentlevel <= 0 &&
20412041
Token::simpleMatch(tok2->link()->previous(), "else {") &&
2042-
!isReturnScope(tok2->link()->tokAt(-2)) &&
2042+
!isReturnScope(tok2->link()->tokAt(-2), settings) &&
20432043
isVariableChanged(tok2->link(), tok2, varid, var->isGlobal(), settings, tokenlist->isCPP())) {
20442044
changeKnownToPossible(values);
20452045
}
@@ -2149,9 +2149,7 @@ static bool valueFlowForward(Token * const startToken,
21492149
truevalues.push_back(v);
21502150
else if (!conditionIsFalse(condTok, programMemory))
21512151
truevalues.push_back(v);
2152-
if (condAlwaysFalse)
2153-
falsevalues.push_back(v);
2154-
else if (conditionIsFalse(condTok, programMemory))
2152+
if (conditionIsFalse(condTok, programMemory))
21552153
falsevalues.push_back(v);
21562154
else if (!subFunction && !conditionIsTrue(condTok, programMemory))
21572155
falsevalues.push_back(v);
@@ -2179,7 +2177,7 @@ static bool valueFlowForward(Token * const startToken,
21792177
// goto '}'
21802178
tok2 = startToken1->link();
21812179

2182-
if (isReturnScope(tok2) || !vfresult) {
2180+
if (isReturnScope(tok2, settings) || !vfresult) {
21832181
if (condAlwaysTrue)
21842182
return false;
21852183
removeValues(values, truevalues);
@@ -2207,7 +2205,7 @@ static bool valueFlowForward(Token * const startToken,
22072205
// goto '}'
22082206
tok2 = startTokenElse->link();
22092207

2210-
if (isReturnScope(tok2) || !vfresult) {
2208+
if (isReturnScope(tok2, settings) || !vfresult) {
22112209
if (condAlwaysFalse)
22122210
return false;
22132211
removeValues(values, falsevalues);
@@ -2283,7 +2281,7 @@ static bool valueFlowForward(Token * const startToken,
22832281
}
22842282

22852283
// stop after conditional return scopes that are executed
2286-
if (isReturnScope(end)) {
2284+
if (isReturnScope(end, settings)) {
22872285
std::list<ValueFlow::Value>::iterator it;
22882286
for (it = values.begin(); it != values.end();) {
22892287
if (conditionIsTrue(tok2->next()->astOperand2(), getProgramMemory(tok2, varid, *it)))
@@ -3722,6 +3720,35 @@ static void valueFlowAfterAssign(TokenList *tokenlist, SymbolDatabase* symboldat
37223720
}
37233721
}
37243722

3723+
static void valueFlowSetConditionToKnown(const Token* tok, std::list<ValueFlow::Value>& values, bool then)
3724+
{
3725+
if (values.size() != 1U)
3726+
return;
3727+
if (values.front().isKnown())
3728+
return;
3729+
if (then && !Token::Match(tok, "==|!|("))
3730+
return;
3731+
if (!then && !Token::Match(tok, "!=|%var%|("))
3732+
return;
3733+
const char * op = "||";
3734+
if (then)
3735+
op = "&&";
3736+
const Token* parent = tok->astParent();
3737+
while (parent && parent->str() == op)
3738+
parent = parent->astParent();
3739+
if (parent && parent->str() == "(")
3740+
values.front().setKnown();
3741+
}
3742+
3743+
static bool isBreakScope(const Token* const endToken)
3744+
{
3745+
if (!Token::simpleMatch(endToken, "}"))
3746+
return false;
3747+
if (!Token::simpleMatch(endToken->link(), "{"))
3748+
return false;
3749+
return Token::findmatch(endToken->link(), "break|goto", endToken);
3750+
}
3751+
37253752
struct ValueFlowConditionHandler {
37263753
struct Condition {
37273754
const Token *vartok;
@@ -3835,6 +3862,10 @@ struct ValueFlowConditionHandler {
38353862
tok2 = parent;
38363863
}
38373864
}
3865+
if (cond.true_values != cond.false_values) {
3866+
check_if = true;
3867+
check_else = true;
3868+
}
38383869

38393870
// determine startToken(s)
38403871
if (check_if && Token::simpleMatch(top->link(), ") {"))
@@ -3849,13 +3880,7 @@ struct ValueFlowConditionHandler {
38493880
if (!startToken)
38503881
continue;
38513882
std::list<ValueFlow::Value> &values = (i == 0 ? cond.true_values : cond.false_values);
3852-
if (values.size() == 1U && Token::Match(tok, "==|!|(")) {
3853-
const Token *parent = tok->astParent();
3854-
while (parent && parent->str() == "&&")
3855-
parent = parent->astParent();
3856-
if (parent && parent->str() == "(")
3857-
values.front().setKnown();
3858-
}
3883+
valueFlowSetConditionToKnown(tok, values, i == 0);
38593884

38603885
bool changed = forward(startTokens[i], startTokens[i]->link(), var, values, true);
38613886
values.front().setPossible();
@@ -3867,7 +3892,6 @@ struct ValueFlowConditionHandler {
38673892
startTokens[i]->link(),
38683893
"valueFlowAfterCondition: " + var->name() + " is changed in conditional block");
38693894
bail = true;
3870-
break;
38713895
}
38723896
}
38733897
if (bail)
@@ -3883,7 +3907,9 @@ struct ValueFlowConditionHandler {
38833907
continue;
38843908
}
38853909

3886-
const bool dead_if = isReturnScope(after);
3910+
bool dead_if = isReturnScope(after, settings) ||
3911+
(tok->astParent() && Token::simpleMatch(tok->astParent()->previous(), "while (") &&
3912+
!isBreakScope(after));
38873913
bool dead_else = false;
38883914

38893915
if (Token::simpleMatch(after, "} else {")) {
@@ -3893,7 +3919,7 @@ struct ValueFlowConditionHandler {
38933919
bailout(tokenlist, errorLogger, after, "possible noreturn scope");
38943920
continue;
38953921
}
3896-
dead_else = isReturnScope(after);
3922+
dead_else = isReturnScope(after, settings);
38973923
}
38983924

38993925
std::list<ValueFlow::Value> *values = nullptr;
@@ -3903,6 +3929,10 @@ struct ValueFlowConditionHandler {
39033929
values = &cond.false_values;
39043930

39053931
if (values) {
3932+
if ((dead_if || dead_else) && !Token::Match(tok->astParent(), "&&|&")) {
3933+
valueFlowSetConditionToKnown(tok, *values, true);
3934+
valueFlowSetConditionToKnown(tok, *values, false);
3935+
}
39063936
// TODO: constValue could be true if there are no assignments in the conditional blocks and
39073937
// perhaps if there are no && and no || in the condition
39083938
bool constValue = false;
@@ -3980,14 +4010,24 @@ static void valueFlowAfterCondition(TokenList *tokenlist,
39804010
vartok = vartok->astOperand1();
39814011
if (!vartok->isName())
39824012
return cond;
4013+
if (astIsPointer(vartok) && true_value.intvalue == 0) {
4014+
if (Token::simpleMatch(tok, "=="))
4015+
false_value.intvalue = 1;
4016+
if (Token::simpleMatch(tok, "!="))
4017+
true_value.intvalue = 1;
4018+
}
4019+
39834020
cond.true_values.push_back(true_value);
39844021
cond.false_values.push_back(false_value);
39854022
cond.vartok = vartok;
39864023
return cond;
39874024
}
39884025

4026+
long long falseIntValue = 0LL;
39894027
if (tok->str() == "!") {
39904028
vartok = tok->astOperand1();
4029+
if (astIsPointer(vartok))
4030+
falseIntValue = 1LL;
39914031

39924032
} else if (tok->isName() && (Token::Match(tok->astParent(), "%oror%|&&") ||
39934033
Token::Match(tok->tokAt(-2), "if|while ( %var% [)=]"))) {
@@ -3997,7 +4037,7 @@ static void valueFlowAfterCondition(TokenList *tokenlist,
39974037
if (!vartok || !vartok->isName())
39984038
return cond;
39994039
cond.true_values.emplace_back(tok, 0LL);
4000-
cond.false_values.emplace_back(tok, 0LL);
4040+
cond.false_values.emplace_back(tok, falseIntValue);
40014041
cond.vartok = vartok;
40024042

40034043
return cond;

0 commit comments

Comments
 (0)