From 0771929518667863264fc07edbdf7edeecc66d5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 17 Mar 2019 13:40:56 +0100 Subject: [PATCH] Buffer overflow: Handling of dynamically allocated buffer --- lib/checkbufferoverrun.cpp | 26 +++++++++++++++----------- test/testbufferoverrun.cpp | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index af1b25ba7..8ef4d9626 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -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 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; } //--------------------------------------------------------------------------- diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 5623b13b8..8ab37e044 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -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)