Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: remap invalid file descriptors using dup2 #44461

Merged
merged 1 commit into from
Oct 26, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions src/node.cc
Original file line number Diff line number Diff line change
Expand Up @@ -608,11 +608,32 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) {
for (auto& s : stdio) {
const int fd = &s - stdio;
if (fstat(fd, &s.stat) == 0) continue;

// Anything but EBADF means something is seriously wrong. We don't
// have to special-case EINTR, fstat() is not interruptible.
if (errno != EBADF) ABORT();
if (fd != open("/dev/null", O_RDWR)) ABORT();
if (fstat(fd, &s.stat) != 0) ABORT();

// If EBADF (file descriptor doesn't exist), open /dev/null and duplicate
// its file descriptor to the invalid file descriptor. Make sure *that*
// file descriptor is valid. POSIX doesn't guarantee the next file
// descriptor open(2) gives us is the lowest available number anymore in
// POSIX.1-2017, which is why dup2(2) is needed.
int null_fd;

do {
null_fd = open("/dev/null", O_RDWR);
} while (null_fd < 0 && errno == EINTR);

if (null_fd != fd) {
int err;

do {
err = dup2(null_fd, fd);
} while (err < 0 && errno == EINTR);
CHECK_EQ(err, 0);
}

if (fstat(fd, &s.stat) < 0) ABORT();
}
}

Expand Down