diff --git a/subsys/storage/flash_map/flash_map_priv.h b/subsys/storage/flash_map/flash_map_priv.h index ab8e378bcd556..5aadd001bec2f 100644 --- a/subsys/storage/flash_map/flash_map_priv.h +++ b/subsys/storage/flash_map/flash_map_priv.h @@ -33,7 +33,7 @@ static inline struct flash_area const *get_flash_area_from_id(int idx) static inline bool is_in_flash_area_bounds(const struct flash_area *fa, off_t off, size_t len) { - return (off >= 0) && ((off + len) <= fa->fa_size); + return (off >= 0) && (off < fa->fa_size) && (len <= (fa->fa_size - off)); } #endif /* ZEPHYR_SUBSYS_STORAGE_FLASH_MAP_PRIV_H_ */ diff --git a/tests/subsys/storage/flash_map/src/main.c b/tests/subsys/storage/flash_map/src/main.c index 555f973d35b96..3b5ef6378954a 100644 --- a/tests/subsys/storage/flash_map/src/main.c +++ b/tests/subsys/storage/flash_map/src/main.c @@ -333,4 +333,24 @@ ZTEST(flash_map, test_flash_area_erase_and_flatten) i + fa->fa_off); } +ZTEST(flash_map, test_parameter_overflows) +{ + const struct flash_area *fa; + uint8_t dst_buf[FLASH_AREA_COPY_SIZE]; + int rc; + + fa = FIXED_PARTITION(SLOT1_PARTITION); + /* -1 cast to size_t gives us max size_t value, added to offset of 1, + * it will overflow to 0. + */ + rc = flash_area_read(fa, 1, dst_buf, (size_t)(-1)); + zassert_equal(rc, -EINVAL, "1: Overflow should have been detected"); + /* Here we have offset 1 below size of area, with added max size_t + * it upper bound of read range should overflow to: + * (max(size_t) + fa->fa_size - 1) mod (max(size_t)) == fa->fa_size - 2 + */ + rc = flash_area_read(fa, fa->fa_size - 1, dst_buf, (size_t)(-1)); + zassert_equal(rc, -EINVAL, "2: Overflow should have been detected"); +} + ZTEST_SUITE(flash_map, NULL, NULL, NULL, NULL, NULL);