From 03e697e11582de1d27f9fd7ddda85d0fa936fa21 Mon Sep 17 00:00:00 2001 From: Qiyuan Zhang Date: Mon, 5 Aug 2024 06:47:21 -0400 Subject: [PATCH] mtd: check the return value of malloc and pread Check the return value of malloc and pread in case they fail. Signed-off-by: Qiyuan Zhang --- package/system/mtd/src/linksys_bootcount.c | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/package/system/mtd/src/linksys_bootcount.c b/package/system/mtd/src/linksys_bootcount.c index d22486203e90c1..42fe815e723998 100644 --- a/package/system/mtd/src/linksys_bootcount.c +++ b/package/system/mtd/src/linksys_bootcount.c @@ -106,10 +106,24 @@ int mtd_resetbc(const char *mtd) } num_bc = mtd_info.size / bc_offset_increment; - curr = malloc(bc_offset_increment); + curr = malloc(bc_offset_increment); + + if(curr == NULL) { + DLOG_ERR("Failed to allocate %u bytes from memory.", bc_offset_increment); + + retval = -6; + goto out; + } for (i = 0; i < num_bc; i++) { - pread(fd, curr, sizeof(struct bootcounter), i * bc_offset_increment); + ret = pread(fd, curr, sizeof(struct bootcounter), i * bc_offset_increment); + + if(ret != sizeof(struct bootcounter)) { + DLOG_ERR("Failed to read boot-count log at offset %08x.", i * bc_offset_increment); + + retval = -5; + goto out; + } /* Existing code assumes erase is to 0xff; left as-is (2019) */ if (curr->magic == 0xffffffff) @@ -179,7 +193,9 @@ int mtd_resetbc(const char *mtd) } out: - if (curr != NULL) free(curr); + if (curr != NULL) + free(curr); + close(fd); return retval; }