Skip to content

Commit b3c392e

Browse files
committed
src: remap invalid file descriptors using dup2
When checking for the validity of the stdio file descriptors (#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). Fixes: nodejs/help#2411 Refs: #875
1 parent 63aba56 commit b3c392e

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

src/node.cc

+10-2
Original file line numberDiff line numberDiff line change
@@ -608,11 +608,19 @@ 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.
619+
const int null_fd = open("/dev/null", O_RDWR);
620+
if (null_fd != fd && dup2(null_fd, fd) != 0) ABORT();
621+
622+
if (fstat(fd, &s.stat) == 0) continue;
623+
ABORT();
616624
}
617625
}
618626

0 commit comments

Comments
 (0)