From 54789f09158f16e8d51c97a5f826f85182cd657e Mon Sep 17 00:00:00 2001 From: Wonsang Ryou Date: Fri, 24 Mar 2017 11:09:21 +0900 Subject: [PATCH] fs/vfs: poll: fix resource leak and memory corruption In case of poll() for multiple file descriptors, if 2nd fd's poll_setup() fails after completing 1st fd's poll_setup(), poll() returns error without releasing 1st fd's setup information. The 1st fd's setup information will be garbage and can cause side effect such as memory curruption. Change-Id: I8bace85b3f8f59c01e3cd0f8888dc85f78739f49 [Ryou: backported from NuttX 157ac4fb and 48107bf0] Signed-off-by: Wonsang Ryou --- os/fs/vfs/fs_poll.c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/os/fs/vfs/fs_poll.c b/os/fs/vfs/fs_poll.c index deb9d5f..d4740a7 100644 --- a/os/fs/vfs/fs_poll.c +++ b/os/fs/vfs/fs_poll.c @@ -182,6 +182,7 @@ static int poll_fdsetup(int fd, FAR struct pollfd *fds, bool setup) static inline int poll_setup(FAR struct pollfd *fds, nfds_t nfds, sem_t *sem) { unsigned int i; + unsigned int j; int ret; /* Process each descriptor in the list */ @@ -207,6 +208,19 @@ static inline int poll_setup(FAR struct pollfd *fds, nfds_t nfds, sem_t *sem) ret = poll_fdsetup(fds[i].fd, &fds[i], true); if (ret < 0) { + /* Setup failed for fds[i]. We now need to teardown previously + * setup fds[0 .. (i - 1)] to release allocated resources and + * to prevent memory corruption by access to freed/released 'fds' + * and 'sem'. + */ + + for (j = 0; j < i; j++) { + (void)poll_fdsetup(fds[j].fd, &fds[j], false); + } + + /* Indicate an error on the file descriptor */ + + fds[i].revents |= POLLERR; return ret; } } -- 2.7.4