Buffer overflow; Fixed FPs when array size is 1

This commit is contained in:
Daniel Marjamäki 2021-05-22 12:13:39 +02:00
parent 1cb48ad418
commit 9a9f14bd8a
2 changed files with 24 additions and 2 deletions

View File

@ -609,6 +609,21 @@ void CheckBufferOverrun::bufferOverflow()
const ValueFlow::Value bufferSize = getBufferSize(argtok);
if (bufferSize.intvalue <= 0)
continue;
// buffer size == 1 => do not warn for dynamic memory
if (bufferSize.intvalue == 1) {
const Token *tok2 = argtok;
while (Token::simpleMatch(tok2->astParent(), "."))
tok2 = tok2->astParent();
while (Token::Match(tok2, "[|."))
tok2 = tok2->astOperand1();
const Variable *var = tok2 ? tok2->variable() : nullptr;
if (var) {
if (var->isPointer())
continue;
if (var->isArgument() && (var->isPointer() || var->isReference()))
continue;
}
}
const bool error = std::none_of(minsizes->begin(), minsizes->end(), [=](const Library::ArgumentChecks::MinSize &minsize) {
return checkBufferSize(tok, minsize, args, bufferSize.intvalue, mSettings);
});

View File

@ -3672,13 +3672,20 @@ private:
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo *x = malloc(sizeof(Foo));\n"
" mysprintf(x.a, \"aa\");\n"
" mysprintf(x->a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Buffer is accessed out of bounds: x.a\n", errout.str());
TODO_ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Buffer is accessed out of bounds: x.a\n", "", errout.str());
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo *x = malloc(sizeof(Foo) + 10);\n"
" mysprintf(x->a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("", errout.str());
check("struct Foo { char a[1]; };\n"
"void f() {\n"
" struct Foo x;\n"
" mysprintf(x.a, \"aa\");\n"
"}", settings);
ASSERT_EQUALS("[test.cpp:4]: (error, inconclusive) Buffer is accessed out of bounds: x.a\n", errout.str());