Skip to content

Commit 326a490

Browse files
committed
src: remap invalid file descriptors using dup2
When checking for the validity of the stdio file descriptors (nodejs#875), ones which don't exist are intended to be remapped to /dev/null (and, if that doesn't work, we abort). This however doesn't work on all platforms and in all cases, and is not anymore required by POSIX; instead, use the `dup2` syscall as a more robust solution (conforms to POSIX.1). Fixes: nodejs/help#2411 Refs: nodejs#875
1 parent 63aba56 commit 326a490

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/node.cc

+23-2
Original file line numberDiff line numberDiff line change
@@ -608,11 +608,32 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) {
608608
for (auto& s : stdio) {
609609
const int fd = &s - stdio;
610610
if (fstat(fd, &s.stat) == 0) continue;
611+
611612
// Anything but EBADF means something is seriously wrong. We don't
612613
// have to special-case EINTR, fstat() is not interruptible.
613614
if (errno != EBADF) ABORT();
614-
if (fd != open("/dev/null", O_RDWR)) ABORT();
615-
if (fstat(fd, &s.stat) != 0) ABORT();
615+
616+
// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
617+
// its file descriptor to the invalid file descriptor. Make sure *that*
618+
// file descriptor is valid. POSIX doesn't guarantee the next file
619+
// descriptor open(2) gives us is the lowest available number anymore in
620+
// POSIX.1-2017, which is why dup2(2) is needed.
621+
int null_fd;
622+
623+
do {
624+
null_fd = open("/dev/null", O_RDWR);
625+
} while (null_fd < 0 && errno == EINTR);
626+
627+
if (null_fd != fd) {
628+
int err;
629+
630+
do {
631+
err = dup2(null_fd, fd);
632+
} while (err < 0 && errno == EINTR);
633+
CHECK_EQ(err, 0);
634+
}
635+
636+
if (fstat(fd, &s.stat) < 0) ABORT();
616637
}
617638
}
618639

0 commit comments

Comments
 (0)