littlefs icon indicating copy to clipboard operation
littlefs copied to clipboard

Add stronger checks for offset in seek

Open lucic71 opened this issue 6 months ago • 4 comments

Previous checks were trying to validate that file->pos does not become negative. However, the method used for checking this contains possible undefined behaivor (UB) because of the signed integer overflow.

This commit adds stronger checks for offset calculation:

  • make sure that ((lfs_soff_t) file->pos + off) is never < 0. Instead of using signed addition to check that (which can possibly lead to UB), use signed comparison: off < 0 && (lfs_soff_t) file->pos < -off. A special check of off against INT32_MIN is added to make sure that -off does not get transformed into -INT32_MIN, which is as well UB.
  • make sure that unsigned overflow does not occur in file->pos + (lfs_off_t) off.

Thoughts:

  • the lseek manual mandates an EOVERFLOW when the new offset cannot be represened in the offset type. I wonder if we want to return that instead of INVAL when an unsigned overflow occurs.

lucic71 avatar Aug 16 '24 15:08 lucic71