diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index c97642b9930..4712b8b4d46 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -631,37 +631,27 @@ ValueFlow::Value CheckBufferOverrunImpl::getBufferSize(const Token *bufTok, cons if (!var || var->isPointer() || (astIsContainer(bufTok) && var->getTypeName() != "std::array")) return ValueFlow::Value(-1); - const MathLib::bigint dim = std::accumulate(var->dimensions().cbegin(), var->dimensions().cend(), MathLib::bigint(1), [](MathLib::bigint i1, const Dimension &dim) { - return i1 * dim.num; - }); + MathLib::bigint dim = 0; + if (!var->dimensionsProduct(dim)) + return ValueFlow::Value(-1); + + MathLib::bigint typeSize; + if (var->isPointerArray()) + typeSize = mSettings.platform.sizeof_pointer; + else + typeSize = bufTok->valueType()->getSizeOf(mSettings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointee); + if (MathLib::mulOverflows(dim - index, typeSize)) + return ValueFlow::Value(-1); ValueFlow::Value v; v.setKnown(); v.valueType = ValueFlow::Value::ValueType::BUFFER_SIZE; - - if (var->isPointerArray()) - v.intvalue = (dim - index) * mSettings.platform.sizeof_pointer; - else { - const size_t typeSize = bufTok->valueType()->getSizeOf(mSettings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointee); - v.intvalue = (dim - index) * typeSize; - } + v.intvalue = (dim - index) * typeSize; return v; } //--------------------------------------------------------------------------- -// Return true if a * b does not fit in a MathLib::bigint -static bool mulOverflows(MathLib::bigint a, MathLib::bigint b) -{ - const MathLib::bigint maxValue = std::numeric_limits::max(); - const MathLib::bigint minValue = std::numeric_limits::min(); - if (a > 0) - return b > 0 ? a > maxValue / b : b < minValue / a; - if (a < 0) - return b > 0 ? a < minValue / b : (b < 0 && a < maxValue / b); - return false; -} - static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::MinSize &minsize, const std::vector &args, ValueFlow::Value& bufferSize, const Settings &settings, const Tokenizer* tokenizer) { const Token * const arg = (minsize.arg > 0 && minsize.arg - 1 < args.size()) ? args[minsize.arg - 1] : nullptr; @@ -686,7 +676,7 @@ static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::Mi break; MathLib::bigint myMinsize = argVal->intvalue; const int baseSize = tokenizer->sizeOfType(minsize.baseType); - const bool overflow = baseSize != 0 && mulOverflows(myMinsize, baseSize); + const bool overflow = baseSize != 0 && MathLib::mulOverflows(myMinsize, baseSize); if (baseSize != 0 && !overflow) myMinsize *= baseSize; const bool ok = !overflow && myMinsize <= bufferSize.intvalue; @@ -704,7 +694,7 @@ static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::Mi break; case Library::ArgumentChecks::MinSize::Type::MUL: if (arg && arg2 && arg->hasKnownIntValue() && arg2->hasKnownIntValue()) { - if (mulOverflows(arg->getKnownIntValue(), arg2->getKnownIntValue())) + if (MathLib::mulOverflows(arg->getKnownIntValue(), arg2->getKnownIntValue())) return false; return (arg->getKnownIntValue() * arg2->getKnownIntValue()) <= bufferSize.intvalue; } @@ -713,7 +703,7 @@ static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::Mi MathLib::bigint myMinsize = minsize.value; const int baseSize = tokenizer->sizeOfType(minsize.baseType); if (baseSize != 0) { - if (mulOverflows(myMinsize, baseSize)) + if (MathLib::mulOverflows(myMinsize, baseSize)) return false; myMinsize *= baseSize; } diff --git a/lib/clangimport.cpp b/lib/clangimport.cpp index 0043f5a3cde..ce037137a30 100644 --- a/lib/clangimport.cpp +++ b/lib/clangimport.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -43,7 +44,6 @@ #include #include #include -#include class Settings; @@ -1638,11 +1638,19 @@ static void setValues(const Tokenizer &tokenizer, const SymbolDatabase *symbolDa MathLib::bigint typeSize = 0; for (const Variable &var: scope.varlist) { - const MathLib::bigint mul = std::accumulate(var.dimensions().cbegin(), var.dimensions().cend(), MathLib::bigint(1), [](MathLib::bigint v, const Dimension& dim) { - return v * dim.num; - }); - if (var.valueType()) - typeSize += mul * var.valueType()->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); + MathLib::bigint mul = 0; + if (!var.dimensionsProduct(mul)) { + typeSize = 0; + break; + } + if (var.valueType()) { + const MathLib::bigint size = var.valueType()->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); + if (MathLib::mulOverflows(mul, size) || mul * size > std::numeric_limits::max() - typeSize) { + typeSize = 0; + break; + } + typeSize += mul * size; + } } scope.definedType->sizeOf = typeSize; } diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index 9aba7118858..f057951eddf 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -1334,6 +1334,17 @@ bool MathLib::isOctalDigit(char c) return (c >= '0' && c <= '7'); } +bool MathLib::mulOverflows(bigint a, bigint b) +{ + const bigint maxValue = std::numeric_limits::max(); + const bigint minValue = std::numeric_limits::min(); + if (a > 0) + return b > 0 ? a > maxValue / b : b < minValue / a; + if (a < 0) + return b > 0 ? a < minValue / b : (b < 0 && a < maxValue / b); + return false; +} + MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('+',v1,v2); diff --git a/lib/mathlib.h b/lib/mathlib.h index bfa1a5b877b..b08e9849ee5 100644 --- a/lib/mathlib.h +++ b/lib/mathlib.h @@ -170,6 +170,9 @@ class CPPCHECKLIB MathLib { */ static bool isOctalDigit(char c); + /** @brief Return true if a * b does not fit in a bigint */ + static bool mulOverflows(bigint a, bigint b); + static unsigned int encodeMultiChar(const std::string& str); }; diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index 26801640e99..59eaea63d28 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -2515,6 +2516,17 @@ bool Variable::isMember() const { return mScope && mScope->isClassOrStructOrUnion(); } +bool Variable::dimensionsProduct(MathLib::bigint &product) const +{ + product = 1; + for (const Dimension &dim : mDimensions) { + if (MathLib::mulOverflows(product, dim.num)) + return false; + product *= dim.num; + } + return true; +} + bool Variable::isPointerArray() const { if (!isArray()) @@ -8683,6 +8695,7 @@ namespace { { size_t total; bool success; + bool overflow; }; } @@ -8697,10 +8710,10 @@ static Result accumulateStructMembers(const Scope* scope, F f, ValueType::Accura const MathLib::bigint bits = var.nameToken() ? var.nameToken()->bits() : -1; if (const ValueType* vt = var.valueType()) { if (vt->type == ValueType::Type::RECORD && vt->typeScope == scope) - return {0, false}; - const MathLib::bigint dim = std::accumulate(var.dimensions().cbegin(), var.dimensions().cend(), MathLib::bigint(1), [](MathLib::bigint i1, const Dimension& dim) { - return i1 * dim.num; - }); + return {0, false, false}; + MathLib::bigint dim = 0; + if (!var.dimensionsProduct(dim)) + return {0, false, true}; if (var.nameToken()->scope() != scope && var.nameToken()->scope()->definedType) { // anonymous union const auto ret = anonScopes.insert(var.nameToken()->scope()); if (ret.second) @@ -8714,9 +8727,9 @@ static Result accumulateStructMembers(const Scope* scope, F f, ValueType::Accura total = f(total, *vt, dim, bits); } if (accuracy == ValueType::Accuracy::ExactOrZero && total == 0 && bits == -1) - return {0, false}; + return {0, false, false}; } - return {total, true}; + return {total, true, false}; } @@ -8797,6 +8810,9 @@ size_t ValueType::getSizeOf( const Settings& settings, Accuracy accuracy, SizeOf if (type == ValueType::Type::RECORD && typeScope) { size_t currentBitCount = 0; size_t currentBitfieldAlloc = 0; + // the size must fit in a MathLib::bigint + const size_t maxSize = std::numeric_limits::max(); + bool overflow = false; auto accHelper = [&](size_t total, const ValueType& vt2, size_t dim, MathLib::bigint nBits) -> size_t { const size_t charBit = settings.platform.char_bit; size_t n = vt2.getSizeOf(settings, accuracy, SizeOf::Pointer, ++maxRecursion); @@ -8827,8 +8843,16 @@ size_t ValueType::getSizeOf( const Settings& settings, Accuracy accuracy, SizeOf currentBitCount += nBits; return ret; } + if (MathLib::mulOverflows(static_cast(n), static_cast(dim))) { + overflow = true; + return accuracy == Accuracy::ExactOrZero ? 0 : total; + } n *= dim; size_t padding = (a - (total % a)) % a; + if (total + padding > maxSize || n > maxSize - total - padding) { + overflow = true; + return accuracy == Accuracy::ExactOrZero ? 0 : total; + } if (currentBitCount > 0) { bool fitsInBitfield = currentBitCount + (n * charBit) <= currentBitfieldAlloc * charBit; bool isAligned = currentBitCount % (charBit * a) == 0; @@ -8843,17 +8867,23 @@ size_t ValueType::getSizeOf( const Settings& settings, Accuracy accuracy, SizeOf return typeScope->type == ScopeType::eUnion ? std::max(total, n) : total + padding + n; }; Result result = accumulateStructMembers(typeScope, accHelper, accuracy, settings); + overflow = overflow || result.overflow; size_t total = result.total; if (currentBitCount > 0) total += currentBitfieldAlloc; if (const ::Type* dt = typeScope->definedType) { total = std::accumulate(dt->derivedFrom.begin(), dt->derivedFrom.end(), total, [&](size_t v, const ::Type::BaseInfo& bi) { - if (bi.type && bi.type->classScope) - v += accumulateStructMembers(bi.type->classScope, accHelper, accuracy, settings).total; + if (bi.type && bi.type->classScope) { + const Result baseResult = accumulateStructMembers(bi.type->classScope, accHelper, accuracy, settings); + if (baseResult.overflow || v > maxSize || baseResult.total > maxSize - v) + overflow = true; + else + v += baseResult.total; + } return v; }); } - if (accuracy == Accuracy::ExactOrZero && total == 0 && !result.success) + if (accuracy == Accuracy::ExactOrZero && (overflow || (total == 0 && !result.success))) return 0; total = std::max(size_t{1}, total); size_t align = getAlignOf(*this, settings, accuracy, sizeOf); diff --git a/lib/symboldatabase.h b/lib/symboldatabase.h index 832bcddeab3..c4199b223fa 100644 --- a/lib/symboldatabase.h +++ b/lib/symboldatabase.h @@ -547,6 +547,13 @@ class CPPCHECKLIB Variable { return mDimensions; } + /** + * Get the number of array elements, the product of all dimension lengths. + * @param[out] product the number of elements + * @return false if the product does not fit in a MathLib::bigint + */ + bool dimensionsProduct(MathLib::bigint &product) const; + /** * Get array dimension length. * @return length of dimension diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 0e0bf5ce385..d1ef0d3efab 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -271,6 +271,7 @@ class TestBufferOverrun : public TestFixture { TEST_CASE(minsize_strlen); TEST_CASE(minsize_mul); TEST_CASE(minsize_overflow); + TEST_CASE(arraysize_overflow); TEST_CASE(unknownType); TEST_CASE(terminateStrncpy1); @@ -4990,6 +4991,51 @@ class TestBufferOverrun : public TestFixture { ASSERT_EQUALS("[test.cpp:3:19]: (error) Buffer is accessed out of bounds: buf [bufferAccessOutOfBounds]\n", errout_str()); } + void arraysize_overflow() { + // the number of array elements must not wrap around + check("void f() {\n" + " char a[0x4000000000000001][4];\n" + " memset(a, 0, 10);\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + + check("void f() {\n" + " char a[0x100000000][0x100000000];\n" + " memset(a, 0, 10);\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + + // the size in bytes must not wrap around + check("void f() {\n" + " int a[0x4000000000000001];\n" + " memset(a, 0, 10);\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + + check("void f() {\n" + " int a[0x4000000000000001][1];\n" + " memset(a, 0, 10);\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + + // the size of a derived class must not wrap around + check("struct B { int i; };\n" + "struct D : B { char m[0x100000000][0x100000000]; };\n" + "void f() {\n" + " D d;\n" + " memset(&d, 0, 10);\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + + check("struct B { int i; };\n" + "struct D : B { char b[0x6000000000000000]; char c[0x6000000000000000]; };\n" + "int f() {\n" + " char buf[2] = {0};\n" + " return buf[sizeof(D)];\n" + "}\n", settings0); + ASSERT_EQUALS("", errout_str()); + } + // extracttests.enable void unknownType() { diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 1e953af1535..03647d9d29b 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -1864,6 +1864,58 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(1U, values.size()); ASSERT_EQUALS(settings.platform.sizeof_int, values.back().intvalue); ASSERT_EQUALS_ENUM(ValueFlow::Value::ValueKind::Known, values.back().valueKind); + + // the number of array elements does not fit in a MathLib::bigint + code = "struct S { char m[0x4000000000000001][4]; };\n" + "x = sizeof(S);\n"; + values = tokenValues(code, "( S"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + // the size in bytes does not fit in a MathLib::bigint + code = "struct S { int m[0x4000000000000001]; };\n" + "x = sizeof(S);\n"; + values = tokenValues(code, "( S"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + // the overflow must not be lost when base classes are added + code = "struct B { int i; };\n" + "struct D : B { int m[0x4000000000000001]; };\n" + "x = sizeof(D);\n"; + values = tokenValues(code, "( D"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + code = "struct B { int i; };\n" + "struct D : B { char m[0x100000000][0x100000000]; };\n" + "x = sizeof(D);\n"; + values = tokenValues(code, "( D"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + code = "struct B { int i; };\n" + "struct D : B { char b[0x6000000000000000]; char c[0x6000000000000000]; };\n" + "x = sizeof(D);\n"; + values = tokenValues(code, "( D"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + code = "struct B { char m[0x100000000][0x100000000]; };\n" + "struct D : B { int i; };\n" + "x = sizeof(D);\n"; + values = tokenValues(code, "( D"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); + + // the sum of the base class sizes does not fit in a MathLib::bigint + code = "struct B1 { char m[0x6000000000000000]; };\n" + "struct B2 { char m[0x6000000000000000]; };\n" + "struct D : B1, B2 { char c; };\n" + "x = sizeof(D);\n"; + values = tokenValues(code, "( D"); + ASSERT_EQUALS(1U, values.size()); + ASSERT(values.back().isImpossible()); } void valueFlowComma()