Refactor and fix "After a strncpy() the buffer should be zero-terminated" checking,
This commit is contained in:
parent
4bc325f077
commit
d3c251f53a
|
@ -267,34 +267,27 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector<std::str
|
|||
if (_settings->_checkCodingStyle)
|
||||
{
|
||||
// check for strncpy which is not terminated
|
||||
if (Token::Match(tok, "strncpy ( %varid% , %any% , %any% )", varid))
|
||||
{
|
||||
const Token *tokSz = tok->tokAt(6);
|
||||
if (tokSz->isNumber())
|
||||
if (Token::Match(tok, "strncpy ( %varid% , %any% , %num% )", varid))
|
||||
{
|
||||
// strncpy takes entire variable length as input size
|
||||
const std::string num = tok->strAt(6);
|
||||
if (MathLib::toLongNumber(num) == total_size)
|
||||
if (MathLib::toLongNumber(tok->strAt(6)) == total_size)
|
||||
{
|
||||
const Token *tok2 = tok->next()->link()->next()->next();
|
||||
const Token *tok2 = tok->next()->link()->next();
|
||||
for (; tok2; tok2 = tok2->next())
|
||||
{
|
||||
if (Token::Match(tok2, "%varid%", tok->tokAt(2)->varId()))
|
||||
if (tok2->varId() == tok->tokAt(2)->varId())
|
||||
{
|
||||
if (!Token::Match(tok2, "%varid% [ %any% ] = 0 ;", tok->tokAt(2)->varId()))
|
||||
{
|
||||
terminateStrncpyError(tok);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Token::Match(tok, "memset|memcpy|memmove|memcmp|strncpy|fgets ( %varid% , %any% , %any% )", varid) ||
|
||||
Token::Match(tok, "memset|memcpy|memmove|memcmp|fgets ( %var% , %varid% , %any% )", varid))
|
||||
{
|
||||
|
|
|
@ -1775,6 +1775,21 @@ private:
|
|||
" bar[99] = 0;\n"
|
||||
"}\n");
|
||||
ASSERT_EQUALS("[test.cpp:4]: (style) After a strncpy() the buffer should be zero-terminated\n", errout.str());
|
||||
|
||||
// Test with invalid code that there is no segfault
|
||||
check("char baz[100];\n"
|
||||
"strncpy(baz, \"var\", sizeof(baz))\n");
|
||||
ASSERT_EQUALS("", errout.str());
|
||||
|
||||
// Test that there are no duplicate error messages
|
||||
check("void foo ( char *bar )\n"
|
||||
"{\n"
|
||||
" char baz[100];\n"
|
||||
" strncpy(baz, bar, sizeof(baz));\n"
|
||||
" foo(baz);\n"
|
||||
" foo(baz);\n"
|
||||
"}\n");
|
||||
ASSERT_EQUALS("[test.cpp:4]: (style) After a strncpy() the buffer should be zero-terminated\n", errout.str());
|
||||
}
|
||||
|
||||
void terminateStrncpy2()
|
||||
|
|
Loading…
Reference in New Issue