Skip to content

Commit 3c69277

Browse files
yoctopucedpgeorge
authored andcommitted
py/objint_longlong: Fix overflow check in mp_obj_int_get_checked.
This is to fix an outstanding TODO. The test cases is using a range as this will exist in all builds, but `mp_obj_get_int` is used in many different parts of code where an overflow is more likely to occur. Signed-off-by: Yoctopuce dev <[email protected]>
1 parent 062e82a commit 3c69277

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

py/objint_longlong.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -308,8 +308,17 @@ mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) {
308308
}
309309

310310
mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) {
311-
// TODO: Check overflow
312-
return mp_obj_int_get_truncated(self_in);
311+
if (mp_obj_is_small_int(self_in)) {
312+
return MP_OBJ_SMALL_INT_VALUE(self_in);
313+
} else {
314+
const mp_obj_int_t *self = self_in;
315+
long long value = self->val;
316+
mp_int_t truncated = (mp_int_t)value;
317+
if ((long long)truncated == value) {
318+
return truncated;
319+
}
320+
}
321+
mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("overflow converting long int to machine word"));
313322
}
314323

315324
mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in) {

tests/basics/int_64_basics.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,22 @@
125125
x = 1 << 62
126126
print('a' * (x + 4 - x))
127127

128+
# test overflow check in mp_obj_get_int_maybe
129+
x = 1 << 32
130+
r = None
131+
try:
132+
r = range(0, x)
133+
except OverflowError:
134+
# 32-bit target, correctly handled the overflow of x
135+
print("ok")
136+
if r is not None:
137+
if len(r) == x:
138+
# 64-bit target, everything is just a small-int
139+
print("ok")
140+
else:
141+
# 32-bit target that did not handle the overflow of x
142+
print("unhandled overflow")
143+
128144
# negative shifts are invalid
129145
try:
130146
print((1 << 48) >> -4)

0 commit comments

Comments
 (0)