From: Wonsang Ryou Date: Fri, 24 Mar 2017 02:09:21 +0000 (+0900) Subject: fs/vfs: poll: fix resource leak and memory corruption X-Git-Tag: 1.1_Public_Release~614^2~373 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=54789f09158f16e8d51c97a5f826f85182cd657e;p=rtos%2Ftinyara.git 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 --- 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; } }