Skip to content

Commit 9268253

Browse files
committed
fix signed overflow in calculate() and MathLib constant folding
1 parent fdc1942 commit 9268253

8 files changed

Lines changed: 82 additions & 17 deletions

File tree

‎Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -628,7 +628,7 @@ $(libcppdir)/keywords.o: lib/keywords.cpp lib/config.h lib/keywords.h lib/standa
628628
$(libcppdir)/library.o: lib/library.cpp externals/tinyxml2/tinyxml2.h lib/astutils.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/refthunk.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenlist.h lib/utils.h lib/vfvalue.h lib/xml.h
629629
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/library.cpp
630630

631-
$(libcppdir)/mathlib.o: lib/mathlib.cpp externals/simplecpp/simplecpp.h lib/config.h lib/errortypes.h lib/mathlib.h lib/smallvector.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vfvalue.h
631+
$(libcppdir)/mathlib.o: lib/mathlib.cpp externals/simplecpp/simplecpp.h lib/calculate.h lib/config.h lib/errortypes.h lib/mathlib.h lib/smallvector.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vfvalue.h
632632
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/mathlib.cpp
633633

634634
$(libcppdir)/path.o: lib/path.cpp externals/simplecpp/simplecpp.h lib/config.h lib/path.h lib/standards.h lib/utils.h

‎lib/calculate.h‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
#include "errortypes.h"
2424
#include <limits>
2525
#include <string>
26+
#include <type_traits>
2627

2728
template<class T>
2829
bool isEqual(T x, T y)
@@ -46,6 +47,39 @@ bool isZero(T x)
4647
return isEqual(x, T(0));
4748
}
4849

50+
/**
51+
* x + y, x - y or x * y. Signed integer overflow is undefined behaviour, so for a signed integer
52+
* type the operation is done on the unsigned type and the result wraps.
53+
*/
54+
template<class T>
55+
T calculateArithmetic(char op, T x, T y, std::true_type /*isSignedInteger*/)
56+
{
57+
using U = typename std::make_unsigned<T>::type;
58+
const U ux = static_cast<U>(x);
59+
const U uy = static_cast<U>(y);
60+
if (op == '+')
61+
return static_cast<T>(ux + uy);
62+
if (op == '-')
63+
return static_cast<T>(ux - uy);
64+
return static_cast<T>(ux * uy);
65+
}
66+
67+
template<class T>
68+
T calculateArithmetic(char op, T x, T y, std::false_type /*isSignedInteger*/)
69+
{
70+
if (op == '+')
71+
return x + y;
72+
if (op == '-')
73+
return x - y;
74+
return x * y;
75+
}
76+
77+
template<class T>
78+
T calculateArithmetic(char op, T x, T y)
79+
{
80+
return calculateArithmetic(op, x, y, std::integral_constant<bool, std::is_integral<T>::value && std::is_signed<T>::value>{});
81+
}
82+
4983
/**
5084
* @throws InternalError thrown in case of unknown operator
5185
*/
@@ -61,13 +95,13 @@ R calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
6195
switch (MathLib::encodeMultiChar(s)) {
6296
case '+':
6397
case '+=':
64-
return wrap(x + y);
98+
return wrap(calculateArithmetic('+', x, y));
6599
case '-':
66100
case '-=':
67-
return wrap(x - y);
101+
return wrap(calculateArithmetic('-', x, y));
68102
case '*':
69103
case '*=':
70-
return wrap(x * y);
104+
return wrap(calculateArithmetic('*', x, y));
71105
case '/':
72106
case '/=':
73107
if (isZero(y) || (std::is_signed<T>{} && y < 0)) {
@@ -126,7 +160,7 @@ R calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
126160
case '<=':
127161
return wrap(x <= y);
128162
case '<=>':
129-
return wrap(x - y);
163+
return wrap(calculateArithmetic('-', x, y));
130164
}
131165
throw InternalError(nullptr, "Unknown operator: " + s);
132166
}

‎lib/mathlib.cpp‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919

2020
#include "mathlib.h"
21+
#include "calculate.h"
2122
#include "errortypes.h"
2223
#include "token.h"
2324
#include "utils.h"
@@ -186,13 +187,9 @@ MathLib::value MathLib::value::calc(char op, const MathLib::value &v1, const Mat
186187
} else {
187188
switch (op) {
188189
case '+':
189-
temp.mIntValue += v2.mIntValue;
190-
break;
191190
case '-':
192-
temp.mIntValue -= v2.mIntValue;
193-
break;
194191
case '*':
195-
temp.mIntValue *= v2.mIntValue;
192+
temp.mIntValue = calculateArithmetic(op, temp.mIntValue, v2.mIntValue);
196193
break;
197194
case '/':
198195
if (v2.mIntValue == 0)
@@ -204,7 +201,11 @@ MathLib::value MathLib::value::calc(char op, const MathLib::value &v1, const Mat
204201
case '%':
205202
if (v2.mIntValue == 0)
206203
throw InternalError(nullptr, "Internal Error: Division by zero");
207-
temp.mIntValue %= v2.mIntValue;
204+
// x % -1 is 0, but the division overflows for the minimum value
205+
if (v2.mIntValue == -1)
206+
temp.mIntValue = 0;
207+
else
208+
temp.mIntValue %= v2.mIntValue;
208209
break;
209210
case '&':
210211
temp.mIntValue &= v2.mIntValue;
@@ -1119,7 +1120,7 @@ std::string MathLib::add(const std::string & first, const std::string & second)
11191120
return (value(first) + value(second)).str();
11201121
#else
11211122
if (MathLib::isInt(first) && MathLib::isInt(second)) {
1122-
return MathLib::toString(toBigNumber(first) + toBigNumber(second)) + intsuffix(first, second);
1123+
return MathLib::toString(calculateArithmetic('+', toBigNumber(first), toBigNumber(second))) + intsuffix(first, second);
11231124
}
11241125

11251126
double d1 = toDoubleNumber(first);
@@ -1141,7 +1142,7 @@ std::string MathLib::subtract(const std::string &first, const std::string &secon
11411142
return (value(first) - value(second)).str();
11421143
#else
11431144
if (MathLib::isInt(first) && MathLib::isInt(second)) {
1144-
return MathLib::toString(toBigNumber(first) - toBigNumber(second)) + intsuffix(first, second);
1145+
return MathLib::toString(calculateArithmetic('-', toBigNumber(first), toBigNumber(second))) + intsuffix(first, second);
11451146
}
11461147

11471148
if (first == second)
@@ -1189,7 +1190,7 @@ std::string MathLib::multiply(const std::string &first, const std::string &secon
11891190
return (value(first) * value(second)).str();
11901191
#else
11911192
if (MathLib::isInt(first) && MathLib::isInt(second)) {
1192-
return MathLib::toString(toBigNumber(first) * toBigNumber(second)) + intsuffix(first, second);
1193+
return MathLib::toString(calculateArithmetic('*', toBigNumber(first), toBigNumber(second))) + intsuffix(first, second);
11931194
}
11941195
return toString(toDoubleNumber(first) * toDoubleNumber(second));
11951196
#endif
@@ -1204,6 +1205,9 @@ std::string MathLib::mod(const std::string &first, const std::string &second)
12041205
const bigint b = toBigNumber(second);
12051206
if (b == 0)
12061207
throw InternalError(nullptr, "Internal Error: Division by zero");
1208+
// x % -1 is 0, but the division overflows for the minimum value
1209+
if (b == -1)
1210+
return "0" + intsuffix(first, second);
12071211
return MathLib::toString(toBigNumber(first) % b) + intsuffix(first, second);
12081212
}
12091213
return toString(std::fmod(toDoubleNumber(first),toDoubleNumber(second)));

‎lib/valueflow.cpp‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,12 +1146,13 @@ static void valueFlowEnumValue(SymbolDatabase & symboldatabase, const Settings &
11461146
if (rhs && rhs->hasKnownIntValue()) {
11471147
enumerator.value = rhs->getKnownIntValue();
11481148
enumerator.value_known = true;
1149-
value = enumerator.value + 1;
1149+
value = calculateArithmetic<MathLib::bigint>('+', enumerator.value, 1);
11501150
prev_enum_is_known = true;
11511151
} else
11521152
prev_enum_is_known = false;
11531153
} else if (prev_enum_is_known) {
1154-
enumerator.value = value++;
1154+
enumerator.value = value;
1155+
value = calculateArithmetic<MathLib::bigint>('+', value, 1);
11551156
enumerator.value_known = true;
11561157
}
11571158
}

‎oss-fuzz/Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ $(libcppdir)/keywords.o: ../lib/keywords.cpp ../lib/config.h ../lib/keywords.h .
297297
$(libcppdir)/library.o: ../lib/library.cpp ../externals/tinyxml2/tinyxml2.h ../lib/astutils.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/refthunk.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/tokenlist.h ../lib/utils.h ../lib/vfvalue.h ../lib/xml.h
298298
$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/library.cpp
299299

300-
$(libcppdir)/mathlib.o: ../lib/mathlib.cpp ../externals/simplecpp/simplecpp.h ../lib/config.h ../lib/errortypes.h ../lib/mathlib.h ../lib/smallvector.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vfvalue.h
300+
$(libcppdir)/mathlib.o: ../lib/mathlib.cpp ../externals/simplecpp/simplecpp.h ../lib/calculate.h ../lib/config.h ../lib/errortypes.h ../lib/mathlib.h ../lib/smallvector.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vfvalue.h
301301
$(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/mathlib.cpp
302302

303303
$(libcppdir)/path.o: ../lib/path.cpp ../externals/simplecpp/simplecpp.h ../lib/config.h ../lib/path.h ../lib/standards.h ../lib/utils.h

‎test/testmathlib.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,13 @@ class TestMathLib : public TestFixture {
157157
ASSERT_THROW_INTERNAL_EQUALS(MathLib::divide("-9223372036854775808", "-1"), INTERNAL, "Internal Error: Division overflow"); // #4520 - out of range => throw
158158
ASSERT_EQUALS("4611686018427387904", MathLib::divide("-9223372036854775808", "-2")); // #6679
159159

160+
// out of range results wrap without signed integer overflow
161+
ASSERT_EQUALS("-9223372036854775808", MathLib::add("9223372036854775807", "1"));
162+
ASSERT_EQUALS("9223372036854775807", MathLib::subtract("-9223372036854775808", "1"));
163+
ASSERT_EQUALS("-2", MathLib::multiply("9223372036854775807", "2"));
164+
ASSERT_EQUALS("0", MathLib::mod("-9223372036854775808", "-1"));
165+
ASSERT_EQUALS("0", MathLib::calculate("-9223372036854775808", "-1", '%'));
166+
160167

161168
// invoke for each supported action
162169
ASSERT_EQUALS("3", MathLib::calculate("2", "1", '+'));

‎test/testsymboldatabase.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include "tokenlist.h"
2929

3030
#include <algorithm>
31+
#include <climits>
3132
#include <cstdint>
3233
#include <cstring>
3334
#include <iterator>
@@ -470,6 +471,7 @@ class TestSymbolDatabase : public TestFixture {
470471
TEST_CASE(enum18);
471472
TEST_CASE(enum19);
472473
TEST_CASE(enum20); // #14419
474+
TEST_CASE(enum21);
473475

474476
TEST_CASE(struct1);
475477

@@ -7113,6 +7115,19 @@ class TestSymbolDatabase : public TestFixture {
71137115
}
71147116
}
71157117

7118+
void enum21() { // implicit values past the maximum wrap without signed integer overflow
7119+
GET_SYMBOL_DB("enum E { A = 0x7FFFFFFFFFFFFFFE, B, C };\n");
7120+
ASSERT(db != nullptr);
7121+
const Scope* scope = db->findScopeByName("E");
7122+
ASSERT(scope);
7123+
const Enumerator* B = scope->findEnumerator("B");
7124+
ASSERT(B && B->value_known);
7125+
ASSERT_EQUALS(0x7FFFFFFFFFFFFFFELL + 1, B->value);
7126+
const Enumerator* C = scope->findEnumerator("C");
7127+
ASSERT(C && C->value_known);
7128+
ASSERT_EQUALS(LLONG_MIN, C->value);
7129+
}
7130+
71167131
void struct1() {
71177132
GET_SYMBOL_DB_C("struct deer {\n"
71187133
" uint16_t a;\n"

‎test/testvalueflow.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1148,6 +1148,10 @@ class TestValueFlow : public TestFixture {
11481148
ASSERT_EQUALS(10, valueOfTok("x = static_cast<int>(10);\n", "( 10 )").intvalue);
11491149
ASSERT_EQUALS(0, valueOfTok("x = sizeof (struct {int a;}) * 0;\n", "*").intvalue);
11501150

1151+
// out of range results wrap without signed integer overflow
1152+
ASSERT_EQUALS(LLONG_MIN, valueOfTok("x = 0x7fffffffffffffff + 1;\n", "+").intvalue);
1153+
ASSERT_EQUALS(-2, valueOfTok("x = 0x7fffffffffffffff * 2;\n", "*").intvalue);
1154+
11511155
// Don't calculate or crash if there is UB or invalid operations
11521156
ASSERT(tokenValues(";-1<<10;\n","<<").empty());
11531157
ASSERT(tokenValues(";10<<-1;\n","<<").empty());

0 commit comments

Comments
 (0)