From c938519d8588b7e57fb534e68ecc8978fcbffcc7 Mon Sep 17 00:00:00 2001 From: Francis Deslauriers Date: Mon, 6 May 2019 14:14:39 -0400 Subject: [PATCH] Fix: fd-cache: fd leak on error path MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit 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 Change-Id: I41662edaa4ff13046e003aec20ac27ff242e338f Reviewed-on: https://review.lttng.org/c/babeltrace/+/1260 Reviewed-by: Jérémie Galarneau --- fd-cache/fd-cache.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/fd-cache/fd-cache.c b/fd-cache/fd-cache.c index c0b6859b..dcb4f598 100644 --- a/fd-cache/fd-cache.c +++ b/fd-cache/fd-cache.c @@ -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: -- 2.34.1