diff --git a/lib/vf_common.cpp b/lib/vf_common.cpp index 9b1d0387f38..3253e14518a 100644 --- a/lib/vf_common.cpp +++ b/lib/vf_common.cpp @@ -98,7 +98,7 @@ namespace ValueFlow MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType* dst, const Platform& platform) { - if (value_size == 0) + if (value_size == 0 || value_size >= sizeof(MathLib::biguint)) return value; const MathLib::biguint unsignedMaxValue = std::numeric_limits::max() >> ((sizeof(unsignedMaxValue) - value_size) * 8); @@ -360,7 +360,7 @@ namespace ValueFlow value.intvalue = 0; } } - if (bit < MathLib::bigint_bits) { + if (bit > 0 && bit < MathLib::bigint_bits) { constexpr MathLib::biguint one = 1; value.intvalue &= (one << bit) - 1; if (sign == ValueType::Sign::SIGNED && value.intvalue & (one << (bit - 1))) { diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index dfbb98ad72c..7036d31c007 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -9266,6 +9266,15 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 2)); ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1)); + + // operands of unknown size: no truncation + code = "int f() {\n" + " int_fast8_t a = 0;\n" + " uint_fast8_t b = 10;\n" + " int x = a == b;\n" + " return x;\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0)); } void valueFlowMod() { @@ -9317,6 +9326,25 @@ class TestValueFlow : public TestFixture { values = tokenValues(code, "--"); ASSERT_EQUALS(1U, values.size()); ASSERT_EQUALS(127LLU, values.back().intvalue); + + // operand wider than 64 bits: no truncation + code = "struct S { int a, b, c; S& operator++(); };\n" + "void f(S s) {\n" + " s = 5000000000LL;\n" + " ++s;\n" + "}\n"; + values = tokenValues(code, "++"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(5000000001LL, values.back().intvalue); + + code = "struct S { long a, b; S& operator--(); };\n" + "void f(S s) {\n" + " s = 5000000000LL;\n" + " --s;\n" + "}\n"; + values = tokenValues(code, "--"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(4999999999LL, values.back().intvalue); } void valueFlowNotNull()