Skip to content

Commit 8d56822

Browse files
obiwacRafaelGSS
authored andcommitted
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, 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: #875 PR-URL: #44461 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Joyee Cheung <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]>
1 parent a415869 commit 8d56822

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
@@ -453,11 +453,32 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) {
453453
for (auto& s : stdio) {
454454
const int fd = &s - stdio;
455455
if (fstat(fd, &s.stat) == 0) continue;
456+
456457
// Anything but EBADF means something is seriously wrong. We don't
457458
// have to special-case EINTR, fstat() is not interruptible.
458459
if (errno != EBADF) ABORT();
459-
if (fd != open("/dev/null", O_RDWR)) ABORT();
460-
if (fstat(fd, &s.stat) != 0) ABORT();
460+
461+
// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
462+
// its file descriptor to the invalid file descriptor. Make sure *that*
463+
// file descriptor is valid. POSIX doesn't guarantee the next file
464+
// descriptor open(2) gives us is the lowest available number anymore in
465+
// POSIX.1-2017, which is why dup2(2) is needed.
466+
int null_fd;
467+
468+
do {
469+
null_fd = open("/dev/null", O_RDWR);
470+
} while (null_fd < 0 && errno == EINTR);
471+
472+
if (null_fd != fd) {
473+
int err;
474+
475+
do {
476+
err = dup2(null_fd, fd);
477+
} while (err < 0 && errno == EINTR);
478+
CHECK_EQ(err, 0);
479+
}
480+
481+
if (fstat(fd, &s.stat) < 0) ABORT();
461482
}
462483
}
463484

0 commit comments

Comments
 (0)