From e2e507c499645e69f06a717cdc5161afec1be6e1 Mon Sep 17 00:00:00 2001 From: Old-Ding <35417409+Old-Ding@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:30:26 +0800 Subject: [PATCH] drivers: fix CFI MTD array bounds checks (#11558) * drivers: fix CFI MTD array bounds checks Generated-by: OpenAI Codex Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com> * drivers: reject truncated CFI erase geometry A truncated erase-region table leaves the full flash size registered with only part of its sector geometry. Fail probing instead of exposing a device whose erase address lookup can select the wrong sector. Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com> * drivers: fix CFI log indentation Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com> --------- Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com> --- components/drivers/mtd/mtd-cfi.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/components/drivers/mtd/mtd-cfi.c b/components/drivers/mtd/mtd-cfi.c index ef93d12b80..3f00b110ca 100644 --- a/components/drivers/mtd/mtd-cfi.c +++ b/components/drivers/mtd/mtd-cfi.c @@ -1066,6 +1066,13 @@ static rt_err_t cfi_flash_dev_probe(struct rt_device *dev, struct cfi_flash_devi fdev->vendor = rt_le16_to_cpu(get_unaligned(&query->primary_id)); fdev->ext_addr = rt_le16_to_cpu(get_unaligned(&query->primary_address)); num_erase_regions = query->num_erase_regions; + if (num_erase_regions > RT_ARRAY_SIZE(query->erase_region_info)) + { + LOG_E("Too many %d (> %d) erase regions found", + num_erase_regions, RT_ARRAY_SIZE(query->erase_region_info)); + err = -RT_EINVAL; + goto _fail; + } if (fdev->ext_addr) { @@ -1138,13 +1145,6 @@ static rt_err_t cfi_flash_dev_probe(struct rt_device *dev, struct cfi_flash_devi for (int i = 0; i < num_erase_regions; ++i) { - if (i > RT_ARRAY_SIZE(query->erase_region_info)) - { - LOG_E("Too many %d (> %d) erase regions found", - num_erase_regions, RT_ARRAY_SIZE(query->erase_region_info)); - break; - } - value = rt_le32_to_cpu(get_unaligned(&query->erase_region_info[i])); erase_region_count = (value & 0xffff) + 1; @@ -1158,7 +1158,7 @@ static rt_err_t cfi_flash_dev_probe(struct rt_device *dev, struct cfi_flash_devi break; } - if (sect_count > RT_ARRAY_SIZE(fdev->sect)) + if (sect_count >= RT_ARRAY_SIZE(fdev->sect)) { LOG_E("Too many %d (> %d) sector found", sect_count, RT_ARRAY_SIZE(fdev->sect));