Fix: fd-cache: fd leak on error path
authorFrancis Deslauriers <francis.deslauriers@efficios.com>
Mon, 6 May 2019 18:14:39 +0000 (14:14 -0400)
committerJérémie Galarneau <jeremie.galarneau@efficios.com>
Tue, 7 May 2019 17:22:37 +0000 (13:22 -0400)
Fixes coverity #1401248

  CID 1401248 (#1 of 1): Resource leak (RESOURCE_LEAK)
  10. leaked_handle: Handle variable fd going out of scope leaks the handle.

Reported-by: Coverity (1401248) Resource leak
Signed-off-by: Francis Deslauriers <francis.deslauriers@efficios.com>
Change-Id: I41662edaa4ff13046e003aec20ac27ff242e338f
Reviewed-on: https://review.lttng.org/c/babeltrace/+/1260
Reviewed-by: Jérémie Galarneau <jeremie.galarneau@efficios.com>
fd-cache/fd-cache.c

index c0b6859bb1077a93682be38cfb8241381e2a27f6..dcb4f59802e9bd5460236ac377c7da055ef4323b 100644 (file)
@@ -135,7 +135,7 @@ struct bt_fd_cache_handle *bt_fd_cache_get_handle(struct bt_fd_cache *fdc,
        struct fd_handle_internal *fd_internal = NULL;
        struct stat statbuf;
        struct file_key fk;
-       int ret;
+       int ret, fd = -1;
 
        ret = stat(path, &statbuf);
        if (ret < 0) {
@@ -156,7 +156,7 @@ struct bt_fd_cache_handle *bt_fd_cache_get_handle(struct bt_fd_cache *fdc,
        if (!fd_internal) {
                struct file_key *file_key;
 
-               int fd = open(path, O_RDONLY);
+               fd = open(path, O_RDONLY);
                if (fd < 0) {
                        BT_LOGE_ERRNO("Failed to open file", "path=%s", path);
                        goto error;
@@ -190,6 +190,18 @@ struct bt_fd_cache_handle *bt_fd_cache_get_handle(struct bt_fd_cache *fdc,
        goto end;
 
 error:
+       /*
+        * Close file descriptor if it was open() and we are currently on error
+        * path.
+        */
+       if (fd != -1) {
+               ret = close(fd);
+               if (ret) {
+                       BT_LOGE_ERRNO("Failed to close file descriptor",
+                               ": fd=%i, path=%s", fd, path);
+               }
+       }
+
        fd_cache_handle_internal_destroy(fd_internal);
        fd_internal = NULL;
 end:
This page took 0.026063 seconds and 4 git commands to generate.