QUERY · ISSUE
signed integer overflow (undefined behavior) in littlefs
bug
While updating #7237 I encountered the following diagnostic from the gcc-10 undefined behavior sanitizer:
--- /home/jepler/src/micropython/tests/results/extmod_vfs_lfs_error.py.exp 2022-11-14 19:56:52.599698807 -0600
+++ /home/jepler/src/micropython/tests/results/extmod_vfs_lfs_error.py.out 2022-11-14 19:56:52.599698807 -0600
@@ -25,4 +25,5 @@
chdir OSError
/
stat OSError
+../../lib/littlefs/lfs2.c:3461:36: runtime error: signed integer overflow: 1073741824 + 1073741824 cannot be represented in type 'int'
seek OSError
FAILURE /home/jepler/src/micropython/tests/results/extmod_vfs_lfs_error.py
By performing the arithmetic as unsigned, then converting to signed for the comparison, the diagnostic goes away. However, I'm not confident this is an appropriate or complete fix for the problem of seek arithmetic in lfs2_file_rawseek, so I didn't file a PR:
diff --git a/lib/littlefs/lfs2.c b/lib/littlefs/lfs2.c
index a9fcffafd..d3795fec8 100644
--- a/lib/littlefs/lfs2.c
+++ b/lib/littlefs/lfs2.c
@@ -3458,10 +3458,10 @@ static lfs2_soff_t lfs2_file_rawseek(lfs2_t *lfs2, lfs2_file_t *file,
if (whence == LFS2_SEEK_SET) {
npos = off;
} else if (whence == LFS2_SEEK_CUR) {
- if ((lfs2_soff_t)file->pos + off < 0) {
+ npos = file->pos + off;
+ if ((lfs2_soff_t)npos < 0) {
return LFS2_ERR_INVAL;
} else {
- npos = file->pos + off;
}
} else if (whence == LFS2_SEEK_END) {
lfs2_soff_t res = lfs2_file_rawsize(lfs2, file) + off;
CANDIDATE · PULL REQUEST
py/objrange: Fix integer overflow in range length calculation
Fixes #18144
Problem:
range_len() calculation stop - start + step causes signed integer overflow with values near sys.maxsize, triggering undefined behavior and incorrect range lengths.
Solution:
Rewrite range_len() to use unsigned arithmetic:
- Separate logic for positive and negative steps
- Calculate length as
ceil(diff / step)using unsigned math - Avoids all signed overflow conditions
Impact:
- Fixes range length calculation for large values
- Eliminates undefined behavior from signed overflow
- Matches CPython's handling of large ranges