2 * SPDX-License-Identifier: ISC
4 * Copyright (c) 2004-2005, 2007, 2010, 2012-2015, 2017-2018
5 * Todd C. Miller <Todd.Miller@sudo.ws>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 * This is an open source non-commercial project. Dear PVS-Studio, please check it.
22 * PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
27 #include <sys/types.h>
33 #ifdef HAVE_PSTAT_GETPROC
34 # include <sys/pstat.h>
41 #ifndef _POSIX_OPEN_MAX
42 # define _POSIX_OPEN_MAX 20
46 * Close all file descriptors greater than or equal to lowfd.
47 * This is the expensive (fallback) method.
50 closefrom_fallback(int lowfd)
55 * Fall back on sysconf(_SC_OPEN_MAX). We avoid checking
56 * resource limits since it is possible to open a file descriptor
57 * and then drop the rlimit such that it is below the open fd.
59 maxfd = sysconf(_SC_OPEN_MAX);
61 maxfd = _POSIX_OPEN_MAX;
63 for (fd = lowfd; fd < maxfd; fd++) {
65 /* Avoid potential libdispatch crash when we close its fds. */
66 (void) fcntl((int) fd, F_SETFD, FD_CLOEXEC);
68 (void) close((int) fd);
74 * Close all file descriptors greater than or equal to lowfd.
75 * We try the fast way first, falling back on the slow method.
80 #if defined(HAVE_PSTAT_GETPROC)
81 struct pst_status pstat;
82 #elif defined(HAVE_DIRFD)
87 /* Try the fast method first, if possible. */
88 #if defined(HAVE_FCNTL_CLOSEM)
89 if (fcntl(lowfd, F_CLOSEM, 0) != -1)
92 #if defined(HAVE_PSTAT_GETPROC)
94 * EOVERFLOW is not a fatal error for the fields we use.
95 * See the "EOVERFLOW Error" section of pstat_getvminfo(3).
97 if (pstat_getproc(&pstat, sizeof(pstat), 0, getpid()) != -1 ||
101 for (fd = lowfd; fd <= pstat.pst_highestfd; fd++)
105 #elif defined(HAVE_DIRFD)
106 /* Use /proc/self/fd (or /dev/fd on macOS) if it exists. */
108 path = _PATH_DEV "fd";
110 path = "/proc/self/fd";
112 if ((dirp = opendir(path)) != NULL) {
114 while ((dent = readdir(dirp)) != NULL) {
116 int fd = strtonum(dent->d_name, lowfd, INT_MAX, &errstr);
117 if (errstr == NULL && fd != dirfd(dirp)) {
119 /* Avoid potential libdispatch crash when we close its fds. */
120 (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
126 (void) closedir(dirp);
129 #endif /* HAVE_DIRFD */
131 /* Do things the slow way. */
132 closefrom_fallback(lowfd);