Check for overflow on addition, subtraction, multiplication of integers

This commit is contained in:
Dianne Skoll
2021-01-30 12:56:37 -05:00
parent 9c287e3fd7
commit 0a9eb07f6f
3 changed files with 32 additions and 0 deletions

View File

@@ -765,7 +765,12 @@ static int Add(void)
/* If both are ints, just add 'em */
if (v2.type == INT_TYPE && v1.type == INT_TYPE) {
int old = v2.v.val;
v2.v.val += v1.v.val;
/* Check for overflow */
if (_private_add_overflow(v2.v.val, v1.v.val, old)) {
return E_2HIGH;
}
PushValStack(v2);
return OK;
}
@@ -855,7 +860,9 @@ static int Subtract(void)
/* If they're both INTs, do subtraction */
if (v1.type == INT_TYPE && v2.type == INT_TYPE) {
int old = v1.v.val;
v1.v.val -= v2.v.val;
if (_private_sub_overflow(v1.v.val, v2.v.val, old)) return E_2HIGH;
PushValStack(v1);
return OK;
}
@@ -919,7 +926,11 @@ static int Multiply(void)
}
if (v1.type == INT_TYPE && v2.type == INT_TYPE) {
int old = v1.v.val;
v1.v.val *= v2.v.val;
if (v2.v.val != 0) {
if (_private_div(v1.v.val, v2.v.val) != old) return E_2HIGH;
}
PushValStack(v1);
return OK;
}

View File

@@ -53,3 +53,7 @@ if (ValStackPtr <= 0) \
return E_VA_STK_UNDER; \
else \
(val) = ValStack[--ValStackPtr]
extern int _private_div(int a, int b);
extern int _private_add_overflow(int result, int b, int old);
extern int _private_sub_overflow(int result, int b, int old);

View File

@@ -123,3 +123,20 @@ int DateOK(int y, int m, int d)
d > DaysInMonth(m, y) ) return 0;
else return 1;
}
/* Functions designed to defeat gcc optimizer */
int _private_div(int a, int b) { return a/b; }
int _private_add_overflow(int result, int b, int old)
{
if (b > 0 && result < old) return 1;
if (b < 0 && result > old) return 1;
return 0;
}
int _private_sub_overflow(int result, int b, int old)
{
if (b < 0 && result < old) return 1;
if (b > 0 && result > old) return 1;
return 0;
}