Skip to content

Commit 3b275f0

Browse files
committed
fix out-of-range shifts in ValueFlow castValue and truncateIntValue
1 parent e1f82c1 commit 3b275f0

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

‎lib/vf_common.cpp‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ namespace ValueFlow
9898

9999
MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType* dst, const Platform& platform)
100100
{
101-
if (value_size == 0)
101+
if (value_size == 0 || value_size >= sizeof(MathLib::biguint))
102102
return value;
103103

104104
const MathLib::biguint unsignedMaxValue = std::numeric_limits<MathLib::biguint>::max() >> ((sizeof(unsignedMaxValue) - value_size) * 8);
@@ -360,7 +360,7 @@ namespace ValueFlow
360360
value.intvalue = 0;
361361
}
362362
}
363-
if (bit < MathLib::bigint_bits) {
363+
if (bit > 0 && bit < MathLib::bigint_bits) {
364364
constexpr MathLib::biguint one = 1;
365365
value.intvalue &= (one << bit) - 1;
366366
if (sign == ValueType::Sign::SIGNED && value.intvalue & (one << (bit - 1))) {

‎test/testvalueflow.cpp‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9266,6 +9266,15 @@ class TestValueFlow : public TestFixture {
92669266
"}\n";
92679267
ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 2));
92689268
ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1));
9269+
9270+
// operands of unknown size: no truncation
9271+
code = "int f() {\n"
9272+
" int_fast8_t a = 0;\n"
9273+
" uint_fast8_t b = 10;\n"
9274+
" int x = a == b;\n"
9275+
" return x;\n"
9276+
"}\n";
9277+
ASSERT_EQUALS(true, testValueOfXKnown(code, 5U, 0));
92699278
}
92709279

92719280
void valueFlowMod() {
@@ -9317,6 +9326,25 @@ class TestValueFlow : public TestFixture {
93179326
values = tokenValues(code, "--");
93189327
ASSERT_EQUALS(1U, values.size());
93199328
ASSERT_EQUALS(127LLU, values.back().intvalue);
9329+
9330+
// operand wider than 64 bits: no truncation
9331+
code = "struct S { int a, b, c; S& operator++(); };\n"
9332+
"void f(S s) {\n"
9333+
" s = 5000000000LL;\n"
9334+
" ++s;\n"
9335+
"}\n";
9336+
values = tokenValues(code, "++");
9337+
ASSERT_EQUALS(1U, values.size());
9338+
ASSERT_EQUALS(5000000001LL, values.back().intvalue);
9339+
9340+
code = "struct S { long a, b; S& operator--(); };\n"
9341+
"void f(S s) {\n"
9342+
" s = 5000000000LL;\n"
9343+
" --s;\n"
9344+
"}\n";
9345+
values = tokenValues(code, "--");
9346+
ASSERT_EQUALS(1U, values.size());
9347+
ASSERT_EQUALS(4999999999LL, values.back().intvalue);
93209348
}
93219349

93229350
void valueFlowNotNull()

0 commit comments

Comments
 (0)