From 118c051e465a0bffe22bb5bc57943f54c4afdc86 Mon Sep 17 00:00:00 2001 From: Mathieu Desnoyers Date: Tue, 15 Dec 2020 09:01:38 -0500 Subject: [PATCH] Fix: stream fd leaks on error Use a regular pattern for all commands: If the command callback takes ownership of a pointer or file descriptor, it sets them to NULL or -1. Therefore, the caller can always try to free the pointer, or close it if it is greater or equal to 0. This eliminates memory and fd leaks on error. Change-Id: I447129ab1672ce4fc6cf3c0baf18dbf27bfcfaf8 Signed-off-by: Mathieu Desnoyers --- liblttng-ust/lttng-ust-abi.c | 3 +++ liblttng-ust/lttng-ust-comm.c | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/liblttng-ust/lttng-ust-abi.c b/liblttng-ust/lttng-ust-abi.c index b5c305a9..77bb90db 100644 --- a/liblttng-ust/lttng-ust-abi.c +++ b/liblttng-ust/lttng-ust-abi.c @@ -1107,6 +1107,9 @@ int lttng_abi_map_stream(int channel_objd, struct lttng_ust_stream *info, info->stream_nr, info->len); if (ret) goto error_add_stream; + /* Take ownership of shm_fd and wakeup_fd. */ + uargs->stream.shm_fd = -1; + uargs->stream.wakeup_fd = -1; return 0; diff --git a/liblttng-ust/lttng-ust-comm.c b/liblttng-ust/lttng-ust-comm.c index ead0d7fe..708b9192 100644 --- a/liblttng-ust/lttng-ust-comm.c +++ b/liblttng-ust/lttng-ust-comm.c @@ -1080,6 +1080,8 @@ int handle_message(struct sock_info *sock_info, } case LTTNG_UST_STREAM: { + int close_ret; + /* Receive shm_fd, wakeup_fd */ ret = ustcomm_recv_stream_from_sessiond(sock, NULL, @@ -1095,6 +1097,22 @@ int handle_message(struct sock_info *sock_info, &args, sock_info); else ret = -ENOSYS; + if (args.stream.shm_fd >= 0) { + lttng_ust_lock_fd_tracker(); + close_ret = close(args.stream.shm_fd); + lttng_ust_unlock_fd_tracker(); + args.stream.shm_fd = -1; + if (close_ret) + PERROR("close"); + } + if (args.stream.wakeup_fd >= 0) { + lttng_ust_lock_fd_tracker(); + close_ret = close(args.stream.wakeup_fd); + lttng_ust_unlock_fd_tracker(); + args.stream.wakeup_fd = -1; + if (close_ret) + PERROR("close"); + } break; } case LTTNG_UST_CONTEXT: -- 2.34.1