Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix seek undefined behavior on signed integer overflow #1027

Merged
merged 2 commits into from
Dec 6, 2024

Conversation

geky
Copy link
Member

@geky geky commented Sep 24, 2024

In the previous implementation of lfs_file_seek, we calculated the new offset using signed arithmetic before checking for possible overflow/underflow conditions. This results in undefined behavior in C.

Fortunately for us, littlefs is now limited to 31-bit file sizes for API reasons, so we don't have to be too clever here. Doing the arithmetic with unsigned integers and just checking if we're in a valid range afterwards should work.


Found by @m-kostrzewa and @lucic71
Original tests showing the issue provided by @m-kostrzewa here: #1002
Alternative fix proposed by @lucic71 here: #1017

Original tests provided by m-kostrzewa, these identify signed overflow
(undefined behavior) when compiled with -fsanitize=undefined.
In the previous implementation of lfs_file_seek, we calculated the new
offset using signed arithmetic before checking for possible
overflow/underflow conditions. This results in undefined behavior in C.

Fortunately for us, littlefs is now limited to 31-bit file sizes for API
reasons, so we don't have to be too clever here. Doing the arithmetic
with unsigned integers and just checking if we're in a valid range
afterwards should work.

Found by m-kostrzewa and lucic71
@geky-bot
Copy link
Collaborator

Tests passed ✓, Code: 17060 B, Stack: 1440 B, Structs: 812 B
Code Stack Structs Coverage
Default 17060 B 1440 B 812 B Lines 2391/2571 lines
Readonly 6190 B 448 B 812 B Branches 1242/1580 branches
Threadsafe 17920 B 1440 B 820 B Benchmarks
Multiversion 17120 B 1440 B 816 B Readed 29369693876 B
Migrate 18756 B 1744 B 816 B Proged 1482874766 B
Error-asserts 17744 B 1432 B 812 B Erased 1568888832 B

@geky geky added this to the v2.10 milestone Dec 6, 2024
@geky geky linked an issue Dec 6, 2024 that may be closed by this pull request
@geky geky merged commit d7a9119 into devel Dec 6, 2024
32 checks passed
@geky geky mentioned this pull request Dec 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants