← index #9957PR #3800
Off-topic · high · value 2.457
QUERY · ISSUE

signed integer overflow (undefined behavior) in littlefs

openby jepleropened 2022-11-15updated 2024-09-02
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

parsenum: avoid undefined behavior parsing floats

closedby jepleropened 2018-05-19updated 2025-03-27

Fuzz testing combined with the undefined behavior sanitizer found that parsing unreasonable float literals like 1e+9999999999999 resulted in undefined behavior due to overflow in signed integer arithmetic.

Many compilers actually implement "wrapping" arithmetic on signed integers. This leads to a concrete, wrong result:

>>> 1e18446744073709551623
10000000.0

note that the exponent value is just 2**64+7, and the incorrect result is 10e7

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied