Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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/checksizeof.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ void CheckSizeofImpl::checkSizeofForArrayParameter()
}

const Variable *var = varTok->variable();
if (var && var->isArray() && var->isArgument() && !var->isReference() && !(var->isStlType() && var->getTypeName() == "std::array"))
if (var && var->isDecayedArrayArgument())
sizeofForArrayParameterError(tok);
}
}
Expand Down
7 changes: 7 additions & 0 deletions lib/symboldatabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2718,6 +2718,13 @@ bool Variable::isStlStringViewType() const
return getFlag(fIsStlType) && valueType() && valueType()->container && valueType()->container->stdStringLike && valueType()->container->view;
}

bool Variable::isDecayedArrayArgument() const
{
if (!isArray() || !isArgument() || isReference())
return false;
return !(isStlType() && getTypeName() == "std::array") || Token::simpleMatch(nameToken()->next(), "[");
}

std::string Variable::getTypeName() const
{
std::string ret;
Expand Down
6 changes: 6 additions & 0 deletions lib/symboldatabase.h
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,12 @@ class CPPCHECKLIB Variable {
return getFlag(fIsArray) && !getFlag(fIsPointer);
}

/**
* Is variable an array function parameter, which is a pointer.
* @return true if array parameter that decays to a pointer, false if not
*/
bool isDecayedArrayArgument() const;

/**
* Is pointer variable.
* @return true if pointer, false otherwise
Expand Down
26 changes: 26 additions & 0 deletions lib/valueflow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -422,9 +422,35 @@ void ValueFlow::combineValueProperties(const ValueFlow::Value &value1, const Val
result.path = value1.path;
}

// Set the dimensions that are known when the array declaration ends at tok, so sizeof of the array is known
static void valueFlowArrayDimensions(const Token* tok)
{
const Token* start = tok->link();
while (Token::simpleMatch(start->previous(), "]"))
start = start->linkAt(-1);
const Token* const nameTok = start->previous();
const Variable* const var = nameTok ? nameTok->variable() : nullptr;
if (!var || var->nameToken() != nameTok || !var->isArray())
return;
for (const Dimension& constDimension : var->dimensions()) {
auto& dimension = const_cast<Dimension&>(constDimension);
if (dimension.known || dimension.num != 0 || !dimension.tok)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI review

This loop also goes over dimensions that come from a template argument, where Token::Match(dimension.tok->previous(), "[<,]") is true. setArrayDimensionsUsingValueFlow() handles those separately, because dimension.tok there is only the first token of the argument and there may be no AST. Here dimension.tok->getKnownValue() returns the value of that first token. Because num is then non-zero, the later pass skips the dimension and never corrects it.

#include <array>
struct S { char c[4]; };
void f() {
    std::array<char, 3 + sizeof(S)> a[2];
    char buf[sizeof(a)];
    buf[5] = 0;
}

On the PR, sizeof(a) gets the value 3, and cppcheck reports Array 'buf[3]' accessed at index 5, which is out of bounds. [arrayIndexOutOfBounds]. Base gives no warning.

One possible fix is to skip dimensions where Token::Match(dimension.tok->previous(), "[<,]") and leave them to setArrayDimensionsUsingValueFlow().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 3565303. valueFlowArrayDimensions() now skips dimensions that come from a template argument ([<,] before dimension.tok) and leaves them to setArrayDimensionsUsingValueFlow(), as you suggested.

Your repro no longer warns, and sizeof(a) is 14. I added it to TestBufferOverrun::array_index_79, where it fails without the change.

continue;
if (Token::Match(dimension.tok->previous(), "[<,]"))
continue;
const ValueFlow::Value* const v = dimension.tok->getKnownValue(ValueFlow::Value::ValueType::INT);
if (v && v->intvalue > 0) {
dimension.known = true;
dimension.num = v->intvalue;
}
}
}

static void valueFlowNumber(TokenList &tokenlist, const Settings& settings)
{
for (Token *tok = tokenlist.front(); tok;) {
if (tok->str() == "]" && !Token::simpleMatch(tok->next(), "["))
valueFlowArrayDimensions(tok);
tok = ValueFlow::valueFlowSetConstantValue(tok, settings);
}

Expand Down
8 changes: 6 additions & 2 deletions lib/vf_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ namespace ValueFlow
if (varid1 &&
sz1->variable() &&
sz1->variable()->isArray() &&
!sz1->variable()->isDecayedArrayArgument() &&
!sz1->variable()->dimensions().empty() &&
sz1->variable()->dimensionKnown(0) &&
Token::Match(sz2->astOperand2(), "*|[") && Token::Match(sz2->astOperand2()->astOperand1(), "%varid%", varid1)) {
Expand All @@ -245,8 +246,11 @@ namespace ValueFlow
} else if (Token::Match(tok2, "%var% )")) {
if (const Variable *var = tok2->variable()) {
// find the size of the type
const bool isPointer = var->isDecayedArrayArgument();
size_t size = 0;
if (var->isEnumType()) {
if (isPointer) {
size = settings.platform.sizeof_pointer;
} else if (var->isEnumType()) {
size = settings.platform.sizeof_int;
if (var->type()->classScope && var->type()->classScope->enumType)
size = getSizeOfType(var->type()->classScope->enumType, settings);
Expand All @@ -262,7 +266,7 @@ namespace ValueFlow
}
// find the number of elements
size_t count = 1;
for (size_t i = 0; i < var->dimensions().size(); ++i) {
for (size_t i = 0; !isPointer && i < var->dimensions().size(); ++i) {
if (var->dimensionKnown(i))
count *= var->dimension(i);
else
Expand Down
26 changes: 26 additions & 0 deletions test/testbufferoverrun.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ class TestBufferOverrun : public TestFixture {
TEST_CASE(array_index_76);
TEST_CASE(array_index_77);
TEST_CASE(array_index_78);
TEST_CASE(array_index_79); // #15225
TEST_CASE(array_index_multidim);
TEST_CASE(array_index_switch_in_for);
TEST_CASE(array_index_for_in_for); // FP: #2634
Expand Down Expand Up @@ -2048,6 +2049,31 @@ class TestBufferOverrun : public TestFixture {
ASSERT_EQUALS("", errout_str());
}

void array_index_79()
{
check("struct S { char c[4]; };\n" // #15225
"void f() {\n"
" char a[10 + sizeof(struct S)];\n"
" a[sizeof(a)] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4:6]: (error) Array 'a[14]' accessed at index 14, which is out of bounds. [arrayIndexOutOfBounds]\n",
errout_str());

check("void f(char a[10]) {\n"
" a[sizeof(a)] = 0;\n"
" a[sizeof(a) / sizeof(a[0])] = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());

check("struct S { char c[4]; };\n"
"void f() {\n"
" std::array<char, 3 + sizeof(S)> a[2];\n"
" char buf[sizeof(a)];\n"
" buf[5] = 0;\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}

void array_index_multidim() {
check("void f()\n"
"{\n"
Expand Down
6 changes: 5 additions & 1 deletion test/testsizeof.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,12 @@ class TestSizeof : public TestFixture {
"}\n"
"int g(std::string a[2]) {\n"
" return sizeof(a);\n"
"}\n"
"int h(std::array<int, 2> a[2]) {\n"
" return sizeof(a);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5:12]: (warning) Using 'sizeof' on array given as function argument returns size of a pointer. [sizeofwithsilentarraypointer]\n",
ASSERT_EQUALS("[test.cpp:5:12]: (warning) Using 'sizeof' on array given as function argument returns size of a pointer. [sizeofwithsilentarraypointer]\n"
"[test.cpp:8:12]: (warning) Using 'sizeof' on array given as function argument returns size of a pointer. [sizeofwithsilentarraypointer]\n",
errout_str());
}

Expand Down
92 changes: 92 additions & 0 deletions test/testvalueflow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,98 @@ class TestValueFlow : public TestFixture {
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(2, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"void f() {\n"
" char a[10 + sizeof(struct S)];\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(14, values.back().intvalue);

code = "void f() {\n"
" short s;\n"
" char a[10 + sizeof(s)];\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(12, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"struct S *p;\n"
"void f() {\n"
" char a[10 + sizeof(*p)];\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(14, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"void f() {\n"
" int a[2 + sizeof(struct S)];\n"
" x = sizeof(a) / sizeof(a[0]);\n"
"}\n";
values = tokenValues(code, "/");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(6, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"struct T { char m[10 + sizeof(struct S)]; };\n"
"void f() {\n"
" x = sizeof(struct T);\n"
"}\n";
values = tokenValues(code, "( struct T )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(14, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"void f() {\n"
" char a[10 + sizeof(struct S)];\n"
" char b[sizeof(a)][2];\n"
" x = sizeof(b);\n"
"}\n";
values = tokenValues(code, "( b )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(28, values.back().intvalue);

code = "void f(char a[10]) {\n" // array parameter is a pointer
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(settings.platform.sizeof_pointer, values.back().intvalue);

code = "struct S { char c[4]; };\n"
"void f(char a[10 + sizeof(struct S)]) {\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(settings.platform.sizeof_pointer, values.back().intvalue);

code = "void f(char (&a)[10]) {\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(10, values.back().intvalue);

code = "void f(std::array<char, 10> a) {\n"
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(10, values.back().intvalue);

code = "void f(std::array<int, 4> a[2]) {\n" // array of std::array parameter is a pointer
" x = sizeof(a);\n"
"}\n";
values = tokenValues(code, "( a )");
ASSERT_EQUALS(1U, values.size());
ASSERT_EQUALS(settings.platform.sizeof_pointer, values.back().intvalue);

#define CHECK(A, B, C, D) \
do { \
code = "enum " A " E " B " { E0, E1 };\n" \
Expand Down
Loading