Integer overflow with large ranges
Port, board and/or hardware
unix port, ci unix_sanitize_undefined_build
MicroPython version
MicroPython v1.27.0-preview.208.gadf6319884 on 2025-09-26; linux [GCC 14.2.0] version
Reproduction
Run the following snippet: import sys; print(range(sys.maxsize)[0])
Expected behaviour
No UBsan diagnostics; the number 0 is printed
Observed behaviour
The following diagnostics are produced:
../../py/objrange.c:115:14: runtime error: signed integer overflow: 9223372036854775807 + 1 cannot be represented in type 'long int'
../../py/objrange.c:117:13: runtime error: signed integer overflow: -9223372036854775808 - 1 cannot be represented in type 'long int'
Additional Information
This is related to the cpydiff documented at https://docs.micropython.org/en/latest/genrst/builtin_types.html#range
There are other misbehaving combinations. For instance, here's one with a step that erroneously produces an empty range:
print(range(0, sys.maxsize, sys.maxsize//2)[-1])
but they all seem to stem from signed integer overflows on those two lines (plus line 119 for negative steps)
113 static mp_int_t range_len(mp_obj_range_t *self) {
114 // When computing length, need to take into account step!=1 and step
<0.
115 mp_int_t len = self->stop - self->start + self->step;
116 if (self->step > 0) {
117 len -= 1;
118 } else {
119 len += 1;
120 }
Code of Conduct
Yes, I agree
-fsanitizer=undefined diagnostics with longlong
Port, board and/or hardware
unix port, longlong variant
MicroPython version
local version based on v1.25.0-387-g17fbc5abdc
Reproduction
- Modify
tools.ci.shto update the longlong build to include ubsan:ci_unix_build_helper VARIANT=longlong MICROPY_USE_COMPILER_PLUGIN=gcc \ CFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute" LDFLAGS_EXTRA="-fsanitize=undefined -fno-sanitize=nonnull-attribute"
}
2. `(set -e; . tools/ci.sh; ci_unix_longlong_build; ci_unix_longlong_run_tests)`
### Expected behaviour
Tests succeed
### Observed behaviour
There are failures. Typical failure:
FAILURE /home/jepler/src/micropython/tests/results/basics_int_64_basics.py
--- /home/jepler/src/micropython/tests/results/basics_int_64_basics.py.exp 2025-07-17 12:00:04.723931234 -0500
+++ /home/jepler/src/micropython/tests/results/basics_int_64_basics.py.out 2025-07-17 12:00:04.727931280 -0500
@@ -117,6 +117,7 @@
0
0
left shift negative
+../../py/objint_longlong.c:215:30: runtime error: left shift of negative value -10000000000000000
-10000000000000000
-10000000000000001
-10000000000000002
4 tests failed: basics/int_64_basics.py micropython/viper_ptr32_store_boundary.py micropython/viper_ptr8_store_boundary.py micropython/viper_ptr16_store_boundary.py
### Additional Information
It might be a nice to add sanitizer builds of longlong (& nanbox?).
### Code of Conduct
Yes, I agree