Blob Blame History Raw
From 58d91636a0269ded8f550c07fa1a8d362685f7c9 Mon Sep 17 00:00:00 2001
From: Coiby Xu <coiby.xu@gmail.com>
Date: Fri, 11 Jun 2021 11:06:59 +0800
Subject: [PATCH 2/8] fix RESOURCE_LEAK error detected by covscan in src/util.c

Fix the following error,
    Error: RESOURCE_LEAK (CWE-772): [#def5]
    python-dmidecode-3.12.2/src/util.c:123: open_fn: Returning handle opened by "open". [Note: The source code implementation of the function has been overridden by a user model.]
    python-dmidecode-3.12.2/src/util.c:123: var_assign: Assigning: "fd" = handle returned from "open(devmem, 0)".
    python-dmidecode-3.12.2/src/util.c:147: noescape: Resource "fd" is not freed or pointed-to in "mmap".
    python-dmidecode-3.12.2/src/util.c:191: leaked_handle: Handle variable "fd" going out of scope leaks the handle.

by initializing fd to -1 moving close(fd) to exit.

Signed-off-by: Coiby Xu <coiby.xu@gmail.com>
---
 src/util.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/src/util.c b/src/util.c
index acef5bd..da97767 100644
--- a/src/util.c
+++ b/src/util.c
@@ -112,7 +112,7 @@ void sigill_handler(int ignore_this) {
 void *mem_chunk(Log_t *logp, size_t base, size_t len, const char *devmem)
 {
         void *p;
-        int fd;
+        int fd = -1;
 
 #ifdef USE_MMAP
         size_t mmoffset;
@@ -182,10 +182,11 @@ void *mem_chunk(Log_t *logp, size_t base, size_t len, const char *devmem)
         }
 #endif /* USE_MMAP */
 
-        if(close(fd) == -1)
-                perror(devmem);
-
  exit:
+        if (fd >= 0) {
+            if(close(fd) == -1)
+                perror(devmem);
+        }
         signal(SIGILL, SIG_DFL);
         sigill_logobj = NULL;
         return p;
-- 
2.31.1