nvram: fix memory leak
authorBangLang Huang <banglang.huang@foxmail.com>
Fri, 24 Feb 2017 02:16:17 +0000 (10:16 +0800)
committerJo-Philipp Wich <jo@mein.io>
Wed, 13 Dec 2017 15:23:39 +0000 (16:23 +0100)
Fix memory leak on nvram_open() and nvram_open_rdonly().

For nvram_open(), the 'fd' should be closed on error, and
mmap_area should be unmap when nvram magic can not be found.

For nvram_open_rdonly(), the 'file' variable should free before
return. Once nvram_find_mtd() return successfully, it will allocate
memory to save mtd device string.

Signed-off-by: BangLang Huang <banglang.huang@foxmail.com>
(cherry picked from commit 1948d8e08c72106a01b359a30217cf92657cc79d)

package/utils/nvram/src/cli.c
package/utils/nvram/src/nvram.c

index 488d641cfcfef49751dd94c2481d3617d5eb6cfb..4f9c77804d793df4839fdd650f37f09fe9ee21fa 100644 (file)
 
 static nvram_handle_t * nvram_open_rdonly(void)
 {
-       const char *file = nvram_find_staging();
+       char *file = nvram_find_staging();
 
        if( file == NULL )
                file = nvram_find_mtd();
 
-       if( file != NULL )
-               return nvram_open(file, NVRAM_RO);
+       if( file != NULL ) {
+               nvram_handle_t *h = nvram_open(file, NVRAM_RO);
+               if( strcmp(file, NVRAM_STAGING) )
+                       free(file);
+               return h;
+       }
 
        return NULL;
 }
index 0e4294391ad69af92d2682ac144518fa20b6e9a5..ca893921076ee17db3e855138f91c28a87d2d1c4 100644 (file)
@@ -380,7 +380,9 @@ nvram_handle_t * nvram_open(const char *file, int rdonly)
 
                        if( offset < 0 )
                        {
+                               munmap(mmap_area, nvram_part_size);
                                free(mtd);
+                               close(fd);
                                return NULL;
                        }
                        else if( (h = malloc(sizeof(nvram_handle_t))) != NULL )
@@ -410,6 +412,7 @@ nvram_handle_t * nvram_open(const char *file, int rdonly)
        }
 
        free(mtd);
+       close(fd);
        return NULL;
 }