[PATCH 1/3] cmd: mtd: Prevent out-of-bound check

Michael Nazzareno Trimarchi michael at amarulasolutions.com
Sun Apr 5 11:06:46 CEST 2026


Hi

On Fri, Apr 3, 2026 at 6:17 PM Miquel Raynal <miquel.raynal at bootlin.com> wrote:
>
> The while() loops searching for the next "good" block is unbounded,
> which means in some cases when looking close to the end of the
> device (or during development purposes) this check may lead to
> unexpected behaviours.
>
> For instance, I observed the SPI NAND core complaining because there was
> a single "target" (as in "die"), but the core was selecting the second
> one, which is simply impossible as it does not exist.
>
> Signed-off-by: Miquel Raynal <miquel.raynal at bootlin.com>
> ---
>  cmd/mtd.c | 12 +++++++++++-
>  1 file changed, 11 insertions(+), 1 deletion(-)
>
> diff --git a/cmd/mtd.c b/cmd/mtd.c
> index 7f25144098bb..d3289ab5edbf 100644
> --- a/cmd/mtd.c
> +++ b/cmd/mtd.c
> @@ -559,8 +559,13 @@ static int do_mtd_io(struct cmd_tbl *cmdtp, int flag, int argc,
>
>         /* Search for the first good block after the given offset */
>         off = start_off;
> -       while (mtd_block_isbad(mtd, off))
> +       while (mtd_block_isbad(mtd, off)) {
>                 off += mtd->erasesize;
> +               if (off >= mtd->size) {
> +                       ret = CMD_RET_FAILURE;
> +                       goto out_put_mtd;
> +               }
> +       }
>
>         led_activity_blink();
>
> @@ -573,6 +578,11 @@ static int do_mtd_io(struct cmd_tbl *cmdtp, int flag, int argc,
>                 if (mtd_is_aligned_with_block_size(mtd, off) &&
>                     mtd_block_isbad(mtd, off)) {
>                         off += mtd->erasesize;
> +                       if (off >= mtd->size) {
> +                               ret = CMD_RET_FAILURE;
> +                               goto out_put_mtd;
> +                       }
> +

Reviewed-by: Michael Trimarchi <michael at amarulasolutions.com>

>                         continue;
>                 }
>
>
> --
> 2.53.0
>


-- 
Michael Nazzareno Trimarchi
Co-Founder & Chief Executive Officer
M. +39 347 913 2170
michael at amarulasolutions.com
__________________________________

Amarula Solutions BV
Joop Geesinkweg 125, 1114 AB, Amsterdam, NL
T. +31 (0)85 111 9172
info at amarulasolutions.com
www.amarulasolutions.com


More information about the U-Boot mailing list