fs/vfs: poll: fix resource leak and memory corruption
authorWonsang Ryou <wonsang.yoo@samsung.com>
Fri, 24 Mar 2017 02:09:21 +0000 (11:09 +0900)
committerHeesub Shin <heesub.shin@samsung.com>
Mon, 17 Apr 2017 09:55:39 +0000 (18:55 +0900)
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 <wonsang.yoo@samsung.com>
os/fs/vfs/fs_poll.c

index deb9d5f..d4740a7 100644 (file)
@@ -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;
                        }
                }