improving checkSizeofForStrncmpSize

This commit is contained in:
PKEuS 2011-12-23 18:11:34 +01:00 committed by Daniel Marjamäki
parent e9d697b636
commit 8213a15b2a
2 changed files with 24 additions and 11 deletions

View File

@ -433,8 +433,9 @@ void CheckOther::sizeofForArrayParameterError(const Token *tok)
void CheckOther::checkSizeofForStrncmpSize() void CheckOther::checkSizeofForStrncmpSize()
{ {
const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase(); const SymbolDatabase *symbolDatabase = _tokenizer->getSymbolDatabase();
const char pattern1[] = "strncmp ( %any% , %any% , sizeof ( %var% ) )"; static const char pattern0[] = "strncmp (";
const char pattern2[] = "strncmp ( %any% , %any% , sizeof %var% )"; static const char pattern1[] = "sizeof ( %var% ) )";
static const char pattern2[] = "sizeof %var% )";
// danmar : this is inconclusive in case the size parameter is // danmar : this is inconclusive in case the size parameter is
// sizeof(char *) by intention. // sizeof(char *) by intention.
@ -442,15 +443,21 @@ void CheckOther::checkSizeofForStrncmpSize()
return; return;
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, pattern1) || Token::Match(tok, pattern2)) { if (Token::Match(tok, pattern0)) {
unsigned short tokIdx = 7; const Token *tokVar = tok->tokAt(2);
if (tok->strAt(tokIdx) == "(") if (tokVar)
++tokIdx; tokVar = tokVar->nextArgument();
const Token *tokVar = tok->tokAt(tokIdx); if (tokVar)
if (tokVar->varId() > 0) { tokVar = tokVar->nextArgument();
const Variable *var = symbolDatabase->getVariableFromVarId(tokVar->varId()); if (Token::Match(tokVar, pattern1) || Token::Match(tokVar, pattern2)) {
if (var && var->nameToken()->strAt(-1) == "*") { tokVar = tokVar->next();
sizeofForStrncmpError(tokVar); if (tokVar->str() == "(")
tokVar = tokVar->next();
if (tokVar->varId() > 0) {
const Variable *var = symbolDatabase->getVariableFromVarId(tokVar->varId());
if (var && var->isPointer()) {
sizeofForStrncmpError(tokVar);
}
} }
} }
} }

View File

@ -4097,6 +4097,12 @@ private:
" return strncmp(buf1, buf1_ex, sizeof(buf1_ex)) == 0;\n" " return strncmp(buf1, buf1_ex, sizeof(buf1_ex)) == 0;\n"
"}"); "}");
ASSERT_EQUALS("[test.cpp:4]: (warning) Passing sizeof(pointer) as the last argument to strncmp.\n", errout.str()); ASSERT_EQUALS("[test.cpp:4]: (warning) Passing sizeof(pointer) as the last argument to strncmp.\n", errout.str());
check(
"int fun(const char *buf1) {\n"
" return strncmp(buf1, foo(buf2), sizeof(buf1)) == 0;\n"
"}");
ASSERT_EQUALS("[test.cpp:2]: (warning) Passing sizeof(pointer) as the last argument to strncmp.\n", errout.str());
} }
void check_signOfUnsignedVariable(const char code[], bool inconclusive=false) { void check_signOfUnsignedVariable(const char code[], bool inconclusive=false) {