Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/astutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2407,7 +2407,7 @@ bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Setti
continue;
conclusive = true;
if (indirect > 0) {
if (!arg->isConst() && arg->isPointer())
if (arg->isPointer() && !(arg->valueType() && arg->valueType()->isConst(indirect)))
return true;
// If const is applied to the pointer, then the value can still be modified
if (Token::simpleMatch(arg->typeEndToken(), "* const"))
Expand Down
51 changes: 35 additions & 16 deletions lib/checkother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,14 @@ static bool isVariableMutableInInitializer(const Token* start, const Token * end
return false;
}

static const Token* isFuncArg(const Token* tok) {
while (Token::simpleMatch(tok, ","))
tok = tok->astParent();
if (Token::simpleMatch(tok, "(") && Token::Match(tok->astOperand1(), "%name% ("))
return tok->astOperand1();
return nullptr;
}

void CheckOther::checkConstVariable()
{
if (!mSettings->severity.isEnabled(Severity::style) || mTokenizer->isC())
Expand Down Expand Up @@ -1433,8 +1441,6 @@ void CheckOther::checkConstVariable()
continue;
if (var->isVolatile())
continue;
if (isAliased(var))
continue;
if (isStructuredBindingVariable(var)) // TODO: check all bound variables
continue;
if (isVariableChanged(var, mSettings, mTokenizer->isCPP()))
Expand All @@ -1446,7 +1452,7 @@ void CheckOther::checkConstVariable()
functionScope = functionScope->nestedIn;
} while (functionScope && !(function = functionScope->function));
}
if (function && Function::returnsReference(function) && !Function::returnsConst(function)) {
if (function && (Function::returnsReference(function) || Function::returnsPointer(function)) && !Function::returnsConst(function)) {
std::vector<const Token*> returns = Function::findReturns(function);
if (std::any_of(returns.cbegin(), returns.cend(), [&](const Token* retTok) {
if (retTok->varId() == var->declarationId())
Expand All @@ -1455,13 +1461,12 @@ void CheckOther::checkConstVariable()
retTok = retTok->astOperand2();
while (Token::simpleMatch(retTok, "."))
retTok = retTok->astOperand2();
if (Token::simpleMatch(retTok, "&"))
retTok = retTok->astOperand1();
return ValueFlow::hasLifetimeToken(getParentLifetime(retTok), var->nameToken());
}))
continue;
}
// Skip if address is taken
if (Token::findmatch(var->nameToken(), "& %varid%", scope->bodyEnd, var->declarationId()))
continue;
// Skip if another non-const variable is initialized with this variable
{
//Is it the right side of an initialization of a non-const reference
Expand All @@ -1474,6 +1479,25 @@ void CheckOther::checkConstVariable()
break;
}
}
if (Token::Match(tok, "& %varid%", var->declarationId())) {
const Token* opTok = tok->astParent();
if (opTok->isComparisonOp() || opTok->isAssignmentOp() || opTok->isCalculation()) {
if (opTok->isComparisonOp() || opTok->isCalculation()) {
if (opTok->astOperand1() != tok)
opTok = opTok->astOperand1();
else
opTok = opTok->astOperand2();
}
if (opTok->valueType() && var->valueType() && opTok->valueType()->isConst(var->valueType()->pointer))
continue;
} else if (const Token* ftok = isFuncArg(opTok)) {
bool inconclusive{};
if (var->valueType() && !isVariableChangedByFunctionCall(ftok, var->valueType()->pointer, var->declarationId(), mSettings, &inconclusive) && !inconclusive)
continue;
}
usedInAssignment = true;
break;
}
if (astIsRangeBasedForDecl(tok) && Token::Match(tok->astParent()->astOperand2(), "%varid%", var->declarationId())) {
const Variable* refvar = tok->astParent()->astOperand1()->variable();
if (refvar && refvar->isReference() && !refvar->isConst()) {
Expand All @@ -1494,7 +1518,7 @@ void CheckOther::checkConstVariable()
castToNonConst = true; // safe guess
break;
}
const bool isConst = 0 != (tok->valueType()->constness & (1 << tok->valueType()->pointer));
const bool isConst = tok->valueType()->isConst(tok->valueType()->pointer);
if (!isConst) {
castToNonConst = true;
break;
Expand Down Expand Up @@ -1565,15 +1589,10 @@ void CheckOther::checkConstPointer()
continue;
} else if (Token::simpleMatch(gparent, "[") && gparent->astOperand2() == parent)
continue;
else if (Token::Match(gparent, "(|,")) {
const Token* ftok = gparent;
while (Token::simpleMatch(ftok, ","))
ftok = ftok->astParent();
if (ftok && Token::Match(ftok->astOperand1(), "%name% (")) {
bool inconclusive{};
if (!isVariableChangedByFunctionCall(ftok->astOperand1(), vt->pointer, var->declarationId(), mSettings, &inconclusive) && !inconclusive)
continue;
}
else if (const Token* ftok = isFuncArg(gparent)) {
bool inconclusive{};
if (!isVariableChangedByFunctionCall(ftok, vt->pointer, var->declarationId(), mSettings, &inconclusive) && !inconclusive)
continue;
}
} else {
if (Token::Match(parent, "%oror%|%comp%|&&|?|!|-"))
Expand Down
7 changes: 7 additions & 0 deletions lib/symboldatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3000,6 +3000,13 @@ bool Function::returnsReference(const Function* function, bool unknown)
});
}

bool Function::returnsPointer(const Function* function, bool unknown)
{
return checkReturns(function, unknown, false, [](UNUSED const Token* defStart, const Token* defEnd) {
return Token::simpleMatch(defEnd->previous(), "*");
});
}

bool Function::returnsStandardType(const Function* function, bool unknown)
{
return checkReturns(function, unknown, true, [](UNUSED const Token* defStart, const Token* defEnd) {
Expand Down
1 change: 1 addition & 0 deletions lib/symboldatabase.h
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,7 @@ class CPPCHECKLIB Function {

static bool returnsConst(const Function* function, bool unknown = false);

static bool returnsPointer(const Function* function, bool unknown = false);
static bool returnsReference(const Function* function, bool unknown = false);
static bool returnsStandardType(const Function* function, bool unknown = false);

Expand Down
2 changes: 0 additions & 2 deletions lib/tokenize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2182,8 +2182,6 @@ void Tokenizer::simplifyTypedefCpp()
syntaxError(tok2);

if (tok2->str() == "=") {
if (!tok2->next())
syntaxError(tok2);
if (tok2->next()->str() == "{")
tok2 = tok2->next()->link()->next();
else if (tok2->next()->str().at(0) == '\"')
Expand Down
111 changes: 109 additions & 2 deletions test/testastutils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,9 @@ class TestAstUtils : public TestFixture {
std::istringstream istr(code);
ASSERT_LOC(tokenizer.tokenize(istr, "test.cpp"), file, line);
const Token * const argtok = Token::findmatch(tokenizer.tokens(), pattern);
return (isVariableChangedByFunctionCall)(argtok, 0, &settings, inconclusive);
ASSERT_LOC(argtok, file, line);
int indirect = (argtok->variable() && argtok->variable()->isArray());
return (isVariableChangedByFunctionCall)(argtok, indirect, &settings, inconclusive);
}

void isVariableChangedByFunctionCallTest() {
Expand All @@ -262,8 +264,113 @@ class TestAstUtils : public TestFixture {
code = "int f(int x) {\n"
"return int(x);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(int* p);\n"
"void f(int x) {\n"
" return g(&x);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(const int* p);\n"
"void f(int x) {\n"
" return g(&x);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "x ) ;", &inconclusive));
TODO_ASSERT_EQUALS(false, true, inconclusive);
ASSERT_EQUALS(false, inconclusive);

code = "void g(int** pp);\n"
"void f(int* p) {\n"
" return g(&p);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "p ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(int* const* pp);\n"
"void f(int* p) {\n"
" return g(&p);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "p ) ;", &inconclusive));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be true because the indirect will be set to 1, which will check that the data is modified and not the pointer.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If indirect is set to 0 then it should be false.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With the new formula and indirect always 0 (as it was before), this fails:

        code = "void g(int a[2]);\n"
               "void f() {\n"
               "    int b[2] = {};\n"
               "    return g(b);\n"
               "}\n";
        ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
        ASSERT_EQUALS(true, inconclusive);

@pfultz2 pfultz2 Mar 23, 2023 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to check for array and up the indirection since arrays are passed by pointer and not by value, I assume.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, a std::array can be passed by value, and since we like to conflate those...

@chrchr-github chrchr-github Mar 26, 2023 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inconclusive was not reset (it is only ever set to true, never false.
So inconclusive is true if we haven't seen a declaration at all, but false if there is a possibly-changing declaration. Shouldn't the result also depend on the function's definition?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's one of the things I want to address with the work started in #4798.

ASSERT_EQUALS(false, inconclusive);

code = "void g(int a[2]);\n"
"void f() {\n"
" int b[2] = {};\n"
" return g(b);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(const int a[2]);\n"
"void f() {\n"
" int b[2] = {};\n"
" return g(b);\n"
"}\n";
inconclusive = false;
TODO_ASSERT_EQUALS(false, true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(std::array<int, 2> a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(std::array<int, 2>& a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(const std::array<int, 2>& a);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(b);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "void g(std::array<int, 2>* p);\n"
"void f() {\n"
" std::array<int, 2> b = {};\n"
" return g(&b);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(true, isVariableChangedByFunctionCall(code, "b ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "struct S {};\n"
"void g(S);\n"
"void f(S* s) {\n"
" g(*s);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "s ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);

code = "struct S {};\n"
"void g(const S&);\n"
"void f(S* s) {\n"
" g(*s);\n"
"}\n";
inconclusive = false;
ASSERT_EQUALS(false, isVariableChangedByFunctionCall(code, "s ) ;", &inconclusive));
ASSERT_EQUALS(false, inconclusive);
}

#define isExpressionChanged(code, var, startPattern, endPattern) \
Expand Down
37 changes: 34 additions & 3 deletions test/testother.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1419,6 +1419,19 @@ class TestOther : public TestFixture {
" }\n"
" return *iter;\n"
"}");
ASSERT_EQUALS("[test.cpp:1]: (style) Parameter 'vec' can be declared as reference to const\n", errout.str());
Comment thread
chrchr-github marked this conversation as resolved.
Resolved

check("auto& foo(std::vector<int>& vec, bool flag) {\n"
" std::vector<int> dummy;\n"
" std::vector<int>::iterator iter;\n"
" if (flag)\n"
" iter = vec.begin();\n"
" else {\n"
" dummy.push_back(42);\n"
" iter = dummy.begin();\n"
" }\n"
" return *iter;\n"
"}");
ASSERT_EQUALS("", errout.str());
}

Expand Down Expand Up @@ -3073,6 +3086,14 @@ class TestOther : public TestFixture {
" return r;\n"
"}\n");
ASSERT_EQUALS("", errout.str());

check("template <typename T> void f(std::vector<T*>& d, const std::vector<T*>& s) {\n" // #11632
" for (const auto& e : s) {\n"
" T* newE = new T(*e);\n"
" d.push_back(newE);\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}

void constParameterCallback() {
Expand Down Expand Up @@ -3406,6 +3427,8 @@ class TestOther : public TestFixture {
"void h(const S&);\n"
"void h(int, int, const S&);\n"
"void i(S&);\n"
"void j(const S*);\n"
"void j(int, int, const S*);\n"
"void f1(S* s) {\n"
" g(*s);\n"
"}\n"
Expand All @@ -3417,10 +3440,18 @@ class TestOther : public TestFixture {
"}\n"
"void f4(S* s) {\n"
" i(*s);\n"
"}\n"
"void f5(S& s) {\n"
" j(&s);\n"
"}\n"
"void f6(S& s) {\n"
" j(1, 2, &s);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:6]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:9]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:12]: (style) Parameter 's' can be declared as pointer to const\n",
ASSERT_EQUALS("[test.cpp:20]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:23]: (style) Parameter 's' can be declared as reference to const\n"
"[test.cpp:8]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:11]: (style) Parameter 's' can be declared as pointer to const\n"
"[test.cpp:14]: (style) Parameter 's' can be declared as pointer to const\n",
errout.str());
}

Expand Down
6 changes: 1 addition & 5 deletions test/testuninitvar.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6551,11 +6551,7 @@ class TestUninitVar : public TestFixture {
" foo(123, &abc);\n"
" return abc.b;\n"
"}");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: abc.a\n"
"[test.cpp:5]: (error) Uninitialized variable: abc.b\n"
"[test.cpp:5]: (error) Uninitialized variable: abc.c\n",
"",
errout.str());
ASSERT_EQUALS("[test.cpp:5]: (error) Uninitialized variable: &abc\n", errout.str());

valueFlowUninit("struct ABC { int a; int b; int c; };\n"
"void foo() {\n"
Expand Down