]> git.ipfire.org Git - thirdparty/openwrt.git/commitdiff
mtd: fix buffer leak and fd leak in mtd_dump() 23706/head
authorAnna Kiri <bredcorn@gmail.com>
Mon, 8 Jun 2026 09:07:05 +0000 (11:07 +0200)
committerJonas Jelonek <jelonek.jonas@gmail.com>
Mon, 8 Jun 2026 14:18:23 +0000 (16:18 +0200)
Two leaks in mtd_dump():

- The buffer allocated with malloc(erasesize) is never freed before
  returning, leaking erasesize bytes on every call.
- The pre-existing malloc-NULL early return path also leaked the just-
  opened fd by returning directly instead of going through cleanup.

Initialize buf to NULL, route the malloc-NULL case through the
existing 'out:' label, and add free(buf) on the cleanup path so both
fd and buf are released consistently on every exit.

Signed-off-by: Anna Kiri <bredcorn@gmail.com>
Link: https://github.com/openwrt/openwrt/pull/23706
Signed-off-by: Jonas Jelonek <jelonek.jonas@gmail.com>
package/system/mtd/src/mtd.c

index 3a388c88104b76ac583419e68f52759b311838f3..e86582a4b40ccd5c03be7e579b30f35437eb996a 100644 (file)
@@ -367,7 +367,7 @@ mtd_dump(const char *mtd, int part_offset, int size)
 {
        int ret = 0, offset = 0;
        int fd;
-       char *buf;
+       char *buf = NULL;
 
        if (quiet < 2)
                fprintf(stderr, "Dumping %s ...\n", mtd);
@@ -385,8 +385,10 @@ mtd_dump(const char *mtd, int part_offset, int size)
                lseek(fd, part_offset, SEEK_SET);
 
        buf = malloc(erasesize);
-       if (!buf)
-               return -1;
+       if (!buf) {
+               ret = -1;
+               goto out;
+       }
 
        do {
                int len = (size > erasesize) ? (erasesize) : (size);
@@ -410,6 +412,7 @@ mtd_dump(const char *mtd, int part_offset, int size)
        } while (size > 0);
 
 out:
+       free(buf);
        close(fd);
        return ret;
 }