From cdf23975bc1aa5a2a90272662c151fd192e57d3c Mon Sep 17 00:00:00 2001 From: Leah Rowe Date: Sun, 26 Jan 2025 06:00:49 +0000 Subject: [PATCH] util/nvmutil: Only allocate needed memory for file We were allocating 128KB even if we only needed 8KB, for example. It's not a lot of memory, but the principle of the matter is that we must respect the user by not wasting their memory. The design of nvmutil is that it will never overflow, because operations are mapped in memory to the exact size of the gbe file, which can be 8KB, 16KB or 128KB, and this is enforced. Signed-off-by: Leah Rowe --- util/nvmutil/nvmutil.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/util/nvmutil/nvmutil.c b/util/nvmutil/nvmutil.c index 7662e446..36862f9d 100644 --- a/util/nvmutil/nvmutil.c +++ b/util/nvmutil/nvmutil.c @@ -31,7 +31,7 @@ uint8_t hextonum(char chs), rhex(void); #define SIZE_64KB 0x10000 #define SIZE_128KB 0x20000 -uint16_t buf16[SIZE_64KB], mac[3] = {0, 0, 0}; +uint16_t mac[3] = {0, 0, 0}, *buf16; size_t partsize, nf, gbe[2]; uint8_t nvmPartChanged[2] = {0, 0}, skipread[2] = {0, 0}; int e = 1, flags, rfd, fd, part, gbeFileChanged = 0; @@ -198,6 +198,10 @@ openFiles(const char *path) void readGbe(void) { + char *buf = malloc(partsize << 1); + if (buf == NULL) + err(errno, "Can't malloc %ld B for '%s'", partsize, filename); + if ((cmd == writeGbe) || (cmd == cmd_copy)) nf = partsize; /* read/write the entire block */ else @@ -207,8 +211,9 @@ readGbe(void) skipread[part ^ 1] = 1; /* only read the user-specified part */ /* we pread per-part, so each part has its own pointer: */ - gbe[0] = (size_t) buf16; + gbe[0] = (size_t) buf; gbe[1] = gbe[0] + partsize; + buf16 = (uint16_t *) buf; for (int p = 0; p < 2; p++) { if (skipread[p])