Skip to content

Commit fc5cbad

Browse files
committed
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 <dev@yoctopuce.com>
1 parent e993f53 commit fc5cbad

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-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: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,17 @@
125125
x = 1 << 62
126126
print('a' * (x + 4 - x))
127127

128+
# test overflow check in mp_obj_get_int_maybe
129+
l = [ 0, 1 ]
130+
x = 1 << 32
131+
try:
132+
if len(l[x:]) == 0:
133+
print('ok')
134+
else:
135+
print('unhandled overflow')
136+
except OverflowError as e:
137+
print('ok')
138+
128139
# negative shifts are invalid
129140
try:
130141
print((1 << 48) >> -4)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy