Skip to content

Commit 508b06a

Browse files
committed
Fixed cppcheck-opensource#6973 (ValueFlow: dont set possible tokvalues in unreachable code)
1 parent f762aff commit 508b06a

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

lib/valueflow.cpp

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1727,6 +1727,10 @@ static void execute(const Token *expr,
17271727
if (!expr)
17281728
*error = true;
17291729

1730+
else if (expr->values.size() == 1U && expr->values.front().isKnown() && !expr->values.front().tokvalue) {
1731+
*result = expr->values.front().intvalue;
1732+
}
1733+
17301734
else if (expr->isNumber()) {
17311735
*result = MathLib::toLongNumber(expr->str());
17321736
if (MathLib::isFloat(expr->str()))
@@ -1838,16 +1842,22 @@ static void execute(const Token *expr,
18381842
}
18391843

18401844
else if (expr->str() == "[" && expr->astOperand1() && expr->astOperand2()) {
1841-
if (expr->astOperand1()->values.size() != 1U) {
1842-
*error = true;
1843-
return;
1845+
const Token *tokvalue = nullptr;
1846+
std::map<unsigned int, const Token *>::iterator var = programMemory->tokvalues.find(expr->astOperand1()->varId());
1847+
if (var != programMemory->tokvalues.end()) {
1848+
tokvalue = var->second;
1849+
} else {
1850+
if (expr->astOperand1()->values.size() != 1U) {
1851+
*error = true;
1852+
return;
1853+
}
1854+
tokvalue = expr->astOperand1()->values.front().tokvalue;
18441855
}
1845-
const ValueFlow::Value val = expr->astOperand1()->values.front();
1846-
if (!val.tokvalue || !val.tokvalue->isLiteral()) {
1856+
if (!tokvalue || !tokvalue->isLiteral()) {
18471857
*error = true;
18481858
return;
18491859
}
1850-
const std::string strValue = val.tokvalue->strValue();
1860+
const std::string strValue = tokvalue->strValue();
18511861
MathLib::bigint index = 0;
18521862
execute(expr->astOperand2(), programMemory, &index, error);
18531863
if (index >= 0 && index < strValue.size())

test/testvalueflow.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -820,6 +820,22 @@ class TestValueFlow : public TestFixture {
820820
"}";
821821
ASSERT_EQUALS(false, testValueOfX(code, 4U, "\"\""));
822822

823+
code = "void f() {\n" // #6973
824+
" char *x = getenv (\"LC_ALL\");\n"
825+
" if (x == NULL)\n"
826+
" x = \"\";\n"
827+
"\n"
828+
" if ( (x[0] == 'U') &&\n" // x can be ""
829+
" (x[1] ?\n" // x can't be ""
830+
" x[3] :\n" // x can't be ""
831+
" x[2] ))\n" // x can't be ""
832+
" {}\n"
833+
"}\n";
834+
ASSERT_EQUALS(true, testValueOfX(code, 6U, "\"\""));
835+
ASSERT_EQUALS(false, testValueOfX(code, 7U, "\"\""));
836+
ASSERT_EQUALS(false, testValueOfX(code, 8U, "\"\""));
837+
ASSERT_EQUALS(false, testValueOfX(code, 9U, "\"\""));
838+
823839
// if/else
824840
code = "void f() {\n"
825841
" int x = 123;\n"

0 commit comments

Comments
 (0)