Skip to content

Commit 7ad5f30

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 (e.g. /dev/null could already have been opened by the acting process and not actually be mapped to the expected file descriptor); instead, use the `dup2` syscall as a more robust solution (conforms to POSIX.1).
1 parent 63aba56 commit 7ad5f30

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/node.cc

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -607,12 +607,24 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) {
607607
// anything.
608608
for (auto& s : stdio) {
609609
const int fd = &s - stdio;
610-
if (fstat(fd, &s.stat) == 0) continue;
610+
if (fstat(fd, &s.stat) == 0)
611+
continue;
612+
611613
// Anything but EBADF means something is seriously wrong. We don't
612614
// have to special-case EINTR, fstat() is not interruptible.
613-
if (errno != EBADF) ABORT();
614-
if (fd != open("/dev/null", O_RDWR)) ABORT();
615-
if (fstat(fd, &s.stat) != 0) ABORT();
615+
if (errno != EBADF)
616+
ABORT();
617+
618+
// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
619+
// its file descriptor to the invalid file descriptor. Make sure *that*
620+
// file descriptor is valid.
621+
int null_fd = open("/dev/null", O_RDWR);
622+
if (dup2(null_fd, fd) != 0)
623+
ABORT();
624+
625+
if (fstat(fd, &s.stat) == 0)
626+
continue;
627+
ABORT();
616628
}
617629
}
618630

0 commit comments

Comments
 (0)