From 004833215d7fa411e9a05d3a50a4929dd0335935 Mon Sep 17 00:00:00 2001 From: Augustin Cavalier Date: Tue, 3 Sep 2024 11:20:07 -0400 Subject: [PATCH] libroot: Return EBADF if a negative FD is specified to fdopendir. And do some minor code cleanups. Fixes #19060. --- src/system/libroot/posix/dirent.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/system/libroot/posix/dirent.cpp b/src/system/libroot/posix/dirent.cpp index f7dbc1e7fd..caa710c86b 100644 --- a/src/system/libroot/posix/dirent.cpp +++ b/src/system/libroot/posix/dirent.cpp @@ -126,7 +126,10 @@ __create_dir_struct(int fd) DIR* fdopendir(int fd) { - DIR* dir; + if (fd < 0) { + __set_errno(EBADF); + return NULL; + } // Since our standard file descriptors can't be used as directory file // descriptors, we have to open a fresh one explicitly. @@ -140,16 +143,16 @@ fdopendir(int fd) // to fdopendir() without changing its state (like for other *at() // functions), we cannot close it now. // We dup2() the new FD to the previous location instead. - if (dup2(dirFD, fd) == -1) + if (dup2(dirFD, fd) == -1) { close(fd); - else { + } else { close(dirFD); dirFD = fd; fcntl(dirFD, F_SETFD, FD_CLOEXEC); // reset close-on-exec which is cleared by dup() } - dir = __create_dir_struct(dirFD); + DIR* dir = __create_dir_struct(dirFD); if (dir == NULL) { close(dirFD); return NULL;