Buffer overflow: Handling of dynamically allocated buffer

This commit is contained in:
Daniel Marjamäki 2019-03-17 13:40:56 +01:00
parent 92f4113b59
commit 0771929518
2 changed files with 31 additions and 11 deletions

View File

@ -328,17 +328,21 @@ size_t CheckBufferOverrun::getBufferSize(const Token *bufTok) const
const Variable *var = bufTok->variable();
if (!var)
return 0;
if (!var->dimensions().empty()) {
MathLib::bigint dim = 1;
for (const Dimension &d : var->dimensions())
dim *= d.num;
if (var->isPointerArray())
return dim * mSettings->sizeof_pointer;
const MathLib::bigint typeSize = bufTok->valueType()->typeSize(*mSettings);
return dim * typeSize;
}
// TODO: For pointers get pointer value..
return 0;
const MathLib::bigint typeSize = bufTok->valueType()->typeSize(*mSettings);
std::vector<Dimension> dimensions;
if (!var->dimensions().empty())
dimensions = var->dimensions();
else
dimensions = getDynamicDimensions(bufTok, typeSize);
if (dimensions.empty())
return 0;
MathLib::bigint dim = 1;
for (const Dimension &d : dimensions)
dim *= d.num;
if (var->isPointerArray())
return dim * mSettings->sizeof_pointer;
return dim * typeSize;
}
//---------------------------------------------------------------------------

View File

@ -241,6 +241,8 @@ private:
// TODO TEST_CASE(negativeMemoryAllocationSizeError) // #389
TEST_CASE(negativeArraySize);
// TODO TEST_CASE(pointerAddition1);
}
@ -3030,6 +3032,12 @@ private:
"}");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' accessed at index 10, which is out of bounds.\n", errout.str());
check("void foo() {\n"
" char *p = malloc(10);\n"
" memset(p, 0, 100);\n"
"}");
ASSERT_EQUALS("[test.cpp:3]: (error) Buffer is accessed out of bounds: p\n", errout.str());
// ticket #842
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
@ -4088,6 +4096,14 @@ private:
"int c[x?y:-1];\n");
ASSERT_EQUALS("", errout.str());
}
void pointerAddition1() {
check("void f() {\n"
" char arr[10];\n"
" p = arr + 20;\n"
"\n");
ASSERT_EQUALS("error", errout.str());
}
};
REGISTER_TEST(TestBufferOverrun)