erofs-utils: misc: Fix potential memory leak in realloc failure path
authorSandeep Dhavale <dhavale@google.com>
Thu, 18 Jul 2024 20:22:04 +0000 (13:22 -0700)
committerGao Xiang <hsiangkao@linux.alibaba.com>
Fri, 19 Jul 2024 08:52:28 +0000 (16:52 +0800)
As realloc returns NULL on failure, the original value will be
overwritten if it is used as lvalue. Fix this by using a temporary
variable to hold the return value and exit with -ENOMEM in case of
failure. This patch fixes 2 of the realloc blocks with similar fix.

Signed-off-by: Sandeep Dhavale <dhavale@google.com>
Link: https://lore.kernel.org/r/20240718202204.1224620-1-dhavale@google.com
Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
fsck/main.c
lib/data.c

index 8ec94861ac6d6b2ca777c0ae8722045d3ae130d6..fb669673a39ef2091fb7141eaa858c4f7fd0ba90 100644 (file)
@@ -507,9 +507,15 @@ static int erofs_verify_inode_data(struct erofs_inode *inode, int outfd)
 
                if (compressed) {
                        if (map.m_llen > buffer_size) {
+                               char *newbuffer;
+
                                buffer_size = map.m_llen;
-                               buffer = realloc(buffer, buffer_size);
-                               BUG_ON(!buffer);
+                               newbuffer = realloc(buffer, buffer_size);
+                               if (!newbuffer) {
+                                       ret = -ENOMEM;
+                                       goto out;
+                               }
+                               buffer = newbuffer;
                        }
                        ret = z_erofs_read_one_data(inode, &map, raw, buffer,
                                                    0, map.m_llen, false);
index a8402ed8ffdb7cbdefd503c83afbda74efdd8fe6..f37f8f0907c9ecbf073b081d17daf95fa9940962 100644 (file)
@@ -337,12 +337,15 @@ static int z_erofs_read_data(struct erofs_inode *inode, char *buffer,
                }
 
                if (map.m_plen > bufsize) {
+                       char *newraw;
+
                        bufsize = map.m_plen;
-                       raw = realloc(raw, bufsize);
-                       if (!raw) {
+                       newraw = realloc(raw, bufsize);
+                       if (!newraw) {
                                ret = -ENOMEM;
                                break;
                        }
+                       raw = newraw;
                }
 
                ret = z_erofs_read_one_data(inode, &map, raw,