Fix: file descriptor leak in get_possible_cpu_mask_from_sysfs
authorMathieu Desnoyers <mathieu.desnoyers@efficios.com>
Mon, 25 Jul 2022 19:53:17 +0000 (15:53 -0400)
committerMathieu Desnoyers <mathieu.desnoyers@efficios.com>
Mon, 25 Jul 2022 19:54:26 +0000 (15:54 -0400)
Found by Coverity:

*** CID 1490808:  Resource leaks  (RESOURCE_LEAK)
/src/common/smp.c: 125 in get_possible_cpu_mask_from_sysfs()
119                                     max_bytes - total_bytes_read);
120
121                     if (bytes_read < 0) {
122                             if (errno == EINTR) {
123                                     continue;        /* retry operation */
124                             } else {
>>>     CID 1490808:  Resource leaks  (RESOURCE_LEAK)
>>>     Handle variable "fd" going out of scope leaks the handle.
125                                     return -1;
126                             }
127                     }
128
129                     total_bytes_read += bytes_read;
130                     assert(total_bytes_read <= max_bytes);

Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Change-Id: I372b1fa2d454eeaa6462fe9c13692983369bea6b

src/common/smp.c

index a4346591c4595c0682e757ed700c724f6c74b99b..d7ba23c4f263b2afec7fd906f2cc525fbd745dbd 100644 (file)
@@ -105,14 +105,14 @@ int get_possible_cpu_mask_from_sysfs(char *buf, size_t max_bytes)
 {
        ssize_t bytes_read = 0;
        size_t total_bytes_read = 0;
-       int fd = 0;
+       int fd = -1, ret = -1;
 
        if (buf == NULL)
-               return -1;
+               goto end;
 
        fd = open("/sys/devices/system/cpu/possible", O_RDONLY);
        if (fd < 0)
-               return -1;
+               goto end;
 
        do {
                bytes_read = read(fd, buf + total_bytes_read,
@@ -122,7 +122,7 @@ int get_possible_cpu_mask_from_sysfs(char *buf, size_t max_bytes)
                        if (errno == EINTR) {
                                continue;       /* retry operation */
                        } else {
-                               return -1;
+                               goto end;
                        }
                }
 
@@ -130,9 +130,6 @@ int get_possible_cpu_mask_from_sysfs(char *buf, size_t max_bytes)
                assert(total_bytes_read <= max_bytes);
        } while (max_bytes > total_bytes_read && bytes_read > 0);
 
-       if (close(fd))
-               PERROR("close");
-
        /*
         * Make sure the mask read is a null terminated string.
         */
@@ -141,7 +138,13 @@ int get_possible_cpu_mask_from_sysfs(char *buf, size_t max_bytes)
        else
                buf[max_bytes - 1] = '\0';
 
-       return total_bytes_read;
+       if (total_bytes_read > INT_MAX)
+               goto end;
+       ret = (int) total_bytes_read;
+end:
+       if (fd >= 0 && close(fd) < 0)
+               PERROR("close");
+       return ret;
 }
 
 /*
This page took 0.026809 seconds and 4 git commands to generate.