2017
[folly.git] / folly / Subprocess.cpp
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef _GNU_SOURCE
18 #define _GNU_SOURCE
19 #endif
20
21 #include <folly/Subprocess.h>
22
23 #if __linux__
24 #include <sys/prctl.h>
25 #endif
26 #include <fcntl.h>
27
28 #include <array>
29 #include <algorithm>
30 #include <system_error>
31
32 #include <boost/container/flat_set.hpp>
33 #include <boost/range/adaptors.hpp>
34
35 #include <glog/logging.h>
36
37 #include <folly/Assume.h>
38 #include <folly/Conv.h>
39 #include <folly/Exception.h>
40 #include <folly/ScopeGuard.h>
41 #include <folly/Shell.h>
42 #include <folly/String.h>
43 #include <folly/io/Cursor.h>
44 #include <folly/portability/Environment.h>
45 #include <folly/portability/Sockets.h>
46 #include <folly/portability/Unistd.h>
47
48 constexpr int kExecFailure = 127;
49 constexpr int kChildFailure = 126;
50
51 namespace folly {
52
53 ProcessReturnCode::ProcessReturnCode(ProcessReturnCode&& p) noexcept
54   : rawStatus_(p.rawStatus_) {
55   p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
56 }
57
58 ProcessReturnCode& ProcessReturnCode::operator=(ProcessReturnCode&& p)
59     noexcept {
60   rawStatus_ = p.rawStatus_;
61   p.rawStatus_ = ProcessReturnCode::RV_NOT_STARTED;
62   return *this;
63 }
64
65 ProcessReturnCode::State ProcessReturnCode::state() const {
66   if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
67   if (rawStatus_ == RV_RUNNING) return RUNNING;
68   if (WIFEXITED(rawStatus_)) return EXITED;
69   if (WIFSIGNALED(rawStatus_)) return KILLED;
70   throw std::runtime_error(to<std::string>(
71       "Invalid ProcessReturnCode: ", rawStatus_));
72 }
73
74 void ProcessReturnCode::enforce(State expected) const {
75   State s = state();
76   if (s != expected) {
77     throw std::logic_error(to<std::string>(
78       "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
79     ));
80   }
81 }
82
83 int ProcessReturnCode::exitStatus() const {
84   enforce(EXITED);
85   return WEXITSTATUS(rawStatus_);
86 }
87
88 int ProcessReturnCode::killSignal() const {
89   enforce(KILLED);
90   return WTERMSIG(rawStatus_);
91 }
92
93 bool ProcessReturnCode::coreDumped() const {
94   enforce(KILLED);
95   return WCOREDUMP(rawStatus_);
96 }
97
98 std::string ProcessReturnCode::str() const {
99   switch (state()) {
100   case NOT_STARTED:
101     return "not started";
102   case RUNNING:
103     return "running";
104   case EXITED:
105     return to<std::string>("exited with status ", exitStatus());
106   case KILLED:
107     return to<std::string>("killed by signal ", killSignal(),
108                            (coreDumped() ? " (core dumped)" : ""));
109   }
110   assume_unreachable();
111 }
112
113 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
114   : returnCode_(rc),
115     what_(returnCode_.str()) {
116 }
117
118 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
119                                            int errCode,
120                                            int errnoValue)
121   : errnoValue_(errnoValue),
122     what_(to<std::string>(errCode == kExecFailure ?
123                             "failed to execute " :
124                             "error preparing to execute ",
125                           executable, ": ", errnoStr(errnoValue))) {
126 }
127
128 namespace {
129
130 // Copy pointers to the given strings in a format suitable for posix_spawn
131 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
132   std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
133   for (size_t i = 0; i < s.size(); i++) {
134     d[i] = s[i].c_str();
135   }
136   d[s.size()] = nullptr;
137   return d;
138 }
139
140 // Check a wait() status, throw on non-successful
141 void checkStatus(ProcessReturnCode returnCode) {
142   if (returnCode.state() != ProcessReturnCode::EXITED ||
143       returnCode.exitStatus() != 0) {
144     throw CalledProcessError(returnCode);
145   }
146 }
147
148 }  // namespace
149
150 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
151   if (action == Subprocess::PIPE) {
152     if (fd == 0) {
153       action = Subprocess::PIPE_IN;
154     } else if (fd == 1 || fd == 2) {
155       action = Subprocess::PIPE_OUT;
156     } else {
157       throw std::invalid_argument(
158           to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
159     }
160   }
161   fdActions_[fd] = action;
162   return *this;
163 }
164
165 Subprocess::Subprocess() {}
166
167 Subprocess::Subprocess(
168     const std::vector<std::string>& argv,
169     const Options& options,
170     const char* executable,
171     const std::vector<std::string>* env) {
172   if (argv.empty()) {
173     throw std::invalid_argument("argv must not be empty");
174   }
175   if (!executable) executable = argv[0].c_str();
176   spawn(cloneStrings(argv), executable, options, env);
177 }
178
179 Subprocess::Subprocess(
180     const std::string& cmd,
181     const Options& options,
182     const std::vector<std::string>* env) {
183   if (options.usePath_) {
184     throw std::invalid_argument("usePath() not allowed when running in shell");
185   }
186
187   std::vector<std::string> argv = {"/bin/sh", "-c", cmd};
188   spawn(cloneStrings(argv), argv[0].c_str(), options, env);
189 }
190
191 Subprocess::~Subprocess() {
192   CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
193     << "Subprocess destroyed without reaping child";
194 }
195
196 namespace {
197
198 struct ChildErrorInfo {
199   int errCode;
200   int errnoValue;
201 };
202
203 [[noreturn]] void childError(int errFd, int errCode, int errnoValue) {
204   ChildErrorInfo info = {errCode, errnoValue};
205   // Write the error information over the pipe to our parent process.
206   // We can't really do anything else if this write call fails.
207   writeNoInt(errFd, &info, sizeof(info));
208   // exit
209   _exit(errCode);
210 }
211
212 }  // namespace
213
214 void Subprocess::setAllNonBlocking() {
215   for (auto& p : pipes_) {
216     int fd = p.pipe.fd();
217     int flags = ::fcntl(fd, F_GETFL);
218     checkUnixError(flags, "fcntl");
219     int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
220     checkUnixError(r, "fcntl");
221   }
222 }
223
224 void Subprocess::spawn(
225     std::unique_ptr<const char*[]> argv,
226     const char* executable,
227     const Options& optionsIn,
228     const std::vector<std::string>* env) {
229   if (optionsIn.usePath_ && env) {
230     throw std::invalid_argument(
231         "usePath() not allowed when overriding environment");
232   }
233
234   // Make a copy, we'll mutate options
235   Options options(optionsIn);
236
237   // On error, close all pipes_ (ignoring errors, but that seems fine here).
238   auto pipesGuard = makeGuard([this] { pipes_.clear(); });
239
240   // Create a pipe to use to receive error information from the child,
241   // in case it fails before calling exec()
242   int errFds[2];
243 #if FOLLY_HAVE_PIPE2
244   checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
245 #else
246   checkUnixError(::pipe(errFds), "pipe");
247 #endif
248   SCOPE_EXIT {
249     CHECK_ERR(::close(errFds[0]));
250     if (errFds[1] >= 0) {
251       CHECK_ERR(::close(errFds[1]));
252     }
253   };
254
255 #if !FOLLY_HAVE_PIPE2
256   // Ask the child to close the read end of the error pipe.
257   checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
258   // Set the close-on-exec flag on the write side of the pipe.
259   // This way the pipe will be closed automatically in the child if execve()
260   // succeeds.  If the exec fails the child can write error information to the
261   // pipe.
262   checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
263 #endif
264
265   // Perform the actual work of setting up pipes then forking and
266   // executing the child.
267   spawnInternal(std::move(argv), executable, options, env, errFds[1]);
268
269   // After spawnInternal() returns the child is alive.  We have to be very
270   // careful about throwing after this point.  We are inside the constructor,
271   // so if we throw the Subprocess object will have never existed, and the
272   // destructor will never be called.
273   //
274   // We should only throw if we got an error via the errFd, and we know the
275   // child has exited and can be immediately waited for.  In all other cases,
276   // we have no way of cleaning up the child.
277
278   // Close writable side of the errFd pipe in the parent process
279   CHECK_ERR(::close(errFds[1]));
280   errFds[1] = -1;
281
282   // Read from the errFd pipe, to tell if the child ran into any errors before
283   // calling exec()
284   readChildErrorPipe(errFds[0], executable);
285
286   // We have fully succeeded now, so release the guard on pipes_
287   pipesGuard.dismiss();
288 }
289
290 void Subprocess::spawnInternal(
291     std::unique_ptr<const char*[]> argv,
292     const char* executable,
293     Options& options,
294     const std::vector<std::string>* env,
295     int errFd) {
296   // Parent work, pre-fork: create pipes
297   std::vector<int> childFds;
298   // Close all of the childFds as we leave this scope
299   SCOPE_EXIT {
300     // These are only pipes, closing them shouldn't fail
301     for (int cfd : childFds) {
302       CHECK_ERR(::close(cfd));
303     }
304   };
305
306   int r;
307   for (auto& p : options.fdActions_) {
308     if (p.second == PIPE_IN || p.second == PIPE_OUT) {
309       int fds[2];
310       // We're setting both ends of the pipe as close-on-exec. The child
311       // doesn't need to reset the flag on its end, as we always dup2() the fd,
312       // and dup2() fds don't share the close-on-exec flag.
313 #if FOLLY_HAVE_PIPE2
314       // If possible, set close-on-exec atomically. Otherwise, a concurrent
315       // Subprocess invocation can fork() between "pipe" and "fnctl",
316       // causing FDs to leak.
317       r = ::pipe2(fds, O_CLOEXEC);
318       checkUnixError(r, "pipe2");
319 #else
320       r = ::pipe(fds);
321       checkUnixError(r, "pipe");
322       r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
323       checkUnixError(r, "set FD_CLOEXEC");
324       r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
325       checkUnixError(r, "set FD_CLOEXEC");
326 #endif
327       pipes_.emplace_back();
328       Pipe& pipe = pipes_.back();
329       pipe.direction = p.second;
330       int cfd;
331       if (p.second == PIPE_IN) {
332         // Child gets reading end
333         pipe.pipe = folly::File(fds[1], /*owns_fd=*/ true);
334         cfd = fds[0];
335       } else {
336         pipe.pipe = folly::File(fds[0], /*owns_fd=*/ true);
337         cfd = fds[1];
338       }
339       p.second = cfd;  // ensure it gets dup2()ed
340       pipe.childFd = p.first;
341       childFds.push_back(cfd);
342     }
343   }
344
345   // This should already be sorted, as options.fdActions_ is
346   DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
347
348   // Note that the const casts below are legit, per
349   // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
350
351   char** argVec = const_cast<char**>(argv.get());
352
353   // Set up environment
354   std::unique_ptr<const char*[]> envHolder;
355   char** envVec;
356   if (env) {
357     envHolder = cloneStrings(*env);
358     envVec = const_cast<char**>(envHolder.get());
359   } else {
360     envVec = environ;
361   }
362
363   // Block all signals around vfork; see http://ewontfix.com/7/.
364   //
365   // As the child may run in the same address space as the parent until
366   // the actual execve() system call, any (custom) signal handlers that
367   // the parent has might alter parent's memory if invoked in the child,
368   // with undefined results.  So we block all signals in the parent before
369   // vfork(), which will cause them to be blocked in the child as well (we
370   // rely on the fact that Linux, just like all sane implementations, only
371   // clones the calling thread).  Then, in the child, we reset all signals
372   // to their default dispositions (while still blocked), and unblock them
373   // (so the exec()ed process inherits the parent's signal mask)
374   //
375   // The parent also unblocks all signals as soon as vfork() returns.
376   sigset_t allBlocked;
377   r = sigfillset(&allBlocked);
378   checkUnixError(r, "sigfillset");
379   sigset_t oldSignals;
380
381   r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
382   checkPosixError(r, "pthread_sigmask");
383   SCOPE_EXIT {
384     // Restore signal mask
385     r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
386     CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r);  // shouldn't fail
387   };
388
389   // Call c_str() here, as it's not necessarily safe after fork.
390   const char* childDir =
391     options.childDir_.empty() ? nullptr : options.childDir_.c_str();
392   pid_t pid = vfork();
393   if (pid == 0) {
394     int errnoValue = prepareChild(options, &oldSignals, childDir);
395     if (errnoValue != 0) {
396       childError(errFd, kChildFailure, errnoValue);
397     }
398
399     errnoValue = runChild(executable, argVec, envVec, options);
400     // If we get here, exec() failed.
401     childError(errFd, kExecFailure, errnoValue);
402   }
403   // In parent.  Make sure vfork() succeeded.
404   checkUnixError(pid, errno, "vfork");
405
406   // Child is alive.  We have to be very careful about throwing after this
407   // point.  We are inside the constructor, so if we throw the Subprocess
408   // object will have never existed, and the destructor will never be called.
409   //
410   // We should only throw if we got an error via the errFd, and we know the
411   // child has exited and can be immediately waited for.  In all other cases,
412   // we have no way of cleaning up the child.
413   pid_ = pid;
414   returnCode_ = ProcessReturnCode(RV_RUNNING);
415 }
416
417 int Subprocess::prepareChild(const Options& options,
418                              const sigset_t* sigmask,
419                              const char* childDir) const {
420   // While all signals are blocked, we must reset their
421   // dispositions to default.
422   for (int sig = 1; sig < NSIG; ++sig) {
423     ::signal(sig, SIG_DFL);
424   }
425
426   {
427     // Unblock signals; restore signal mask.
428     int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
429     if (r != 0) {
430       return r;  // pthread_sigmask() returns an errno value
431     }
432   }
433
434   // Change the working directory, if one is given
435   if (childDir) {
436     if (::chdir(childDir) == -1) {
437       return errno;
438     }
439   }
440
441   // We don't have to explicitly close the parent's end of all pipes,
442   // as they all have the FD_CLOEXEC flag set and will be closed at
443   // exec time.
444
445   // Close all fds that we're supposed to close.
446   for (auto& p : options.fdActions_) {
447     if (p.second == CLOSE) {
448       if (::close(p.first) == -1) {
449         return errno;
450       }
451     } else if (p.second != p.first) {
452       if (::dup2(p.second, p.first) == -1) {
453         return errno;
454       }
455     }
456   }
457
458   // If requested, close all other file descriptors.  Don't close
459   // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
460   // Ignore errors.
461   if (options.closeOtherFds_) {
462     for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
463       if (options.fdActions_.count(fd) == 0) {
464         ::close(fd);
465       }
466     }
467   }
468
469 #if __linux__
470   // Opt to receive signal on parent death, if requested
471   if (options.parentDeathSignal_ != 0) {
472     const auto parentDeathSignal =
473         static_cast<unsigned long>(options.parentDeathSignal_);
474     if (prctl(PR_SET_PDEATHSIG, parentDeathSignal, 0, 0, 0) == -1) {
475       return errno;
476     }
477   }
478 #endif
479
480   if (options.processGroupLeader_) {
481     if (setpgrp() == -1) {
482       return errno;
483     }
484   }
485
486   // The user callback comes last, so that the child is otherwise all set up.
487   if (options.dangerousPostForkPreExecCallback_) {
488     if (int error = (*options.dangerousPostForkPreExecCallback_)()) {
489       return error;
490     }
491   }
492
493   return 0;
494 }
495
496 int Subprocess::runChild(const char* executable,
497                          char** argv, char** env,
498                          const Options& options) const {
499   // Now, finally, exec.
500   if (options.usePath_) {
501     ::execvp(executable, argv);
502   } else {
503     ::execve(executable, argv, env);
504   }
505   return errno;
506 }
507
508 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
509   ChildErrorInfo info;
510   auto rc = readNoInt(pfd, &info, sizeof(info));
511   if (rc == 0) {
512     // No data means the child executed successfully, and the pipe
513     // was closed due to the close-on-exec flag being set.
514     return;
515   } else if (rc != sizeof(ChildErrorInfo)) {
516     // An error occurred trying to read from the pipe, or we got a partial read.
517     // Neither of these cases should really occur in practice.
518     //
519     // We can't get any error data from the child in this case, and we don't
520     // know if it is successfully running or not.  All we can do is to return
521     // normally, as if the child executed successfully.  If something bad
522     // happened the caller should at least get a non-normal exit status from
523     // the child.
524     LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
525       "rc=" << rc << ", errno=" << errno;
526     return;
527   }
528
529   // We got error data from the child.  The child should exit immediately in
530   // this case, so wait on it to clean up.
531   wait();
532
533   // Throw to signal the error
534   throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
535 }
536
537 ProcessReturnCode Subprocess::poll() {
538   returnCode_.enforce(ProcessReturnCode::RUNNING);
539   DCHECK_GT(pid_, 0);
540   int status;
541   pid_t found = ::waitpid(pid_, &status, WNOHANG);
542   // The spec guarantees that EINTR does not occur with WNOHANG, so the only
543   // two remaining errors are ECHILD (other code reaped the child?), or
544   // EINVAL (cosmic rays?), both of which merit an abort:
545   PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
546   if (found != 0) {
547     // Though the child process had quit, this call does not close the pipes
548     // since its descendants may still be using them.
549     returnCode_ = ProcessReturnCode(status);
550     pid_ = -1;
551   }
552   return returnCode_;
553 }
554
555 bool Subprocess::pollChecked() {
556   if (poll().state() == ProcessReturnCode::RUNNING) {
557     return false;
558   }
559   checkStatus(returnCode_);
560   return true;
561 }
562
563 ProcessReturnCode Subprocess::wait() {
564   returnCode_.enforce(ProcessReturnCode::RUNNING);
565   DCHECK_GT(pid_, 0);
566   int status;
567   pid_t found;
568   do {
569     found = ::waitpid(pid_, &status, 0);
570   } while (found == -1 && errno == EINTR);
571   // The only two remaining errors are ECHILD (other code reaped the
572   // child?), or EINVAL (cosmic rays?), and both merit an abort:
573   PCHECK(found != -1) << "waitpid(" << pid_ << ", &status, WNOHANG)";
574   // Though the child process had quit, this call does not close the pipes
575   // since its descendants may still be using them.
576   DCHECK_EQ(found, pid_);
577   returnCode_ = ProcessReturnCode(status);
578   pid_ = -1;
579   return returnCode_;
580 }
581
582 void Subprocess::waitChecked() {
583   wait();
584   checkStatus(returnCode_);
585 }
586
587 void Subprocess::sendSignal(int signal) {
588   returnCode_.enforce(ProcessReturnCode::RUNNING);
589   int r = ::kill(pid_, signal);
590   checkUnixError(r, "kill");
591 }
592
593 pid_t Subprocess::pid() const {
594   return pid_;
595 }
596
597 namespace {
598
599 ByteRange queueFront(const IOBufQueue& queue) {
600   auto* p = queue.front();
601   if (!p) {
602     return ByteRange{};
603   }
604   return io::Cursor(p).peekBytes();
605 }
606
607 // fd write
608 bool handleWrite(int fd, IOBufQueue& queue) {
609   for (;;) {
610     auto b = queueFront(queue);
611     if (b.empty()) {
612       return true;  // EOF
613     }
614
615     ssize_t n = writeNoInt(fd, b.data(), b.size());
616     if (n == -1 && errno == EAGAIN) {
617       return false;
618     }
619     checkUnixError(n, "write");
620     queue.trimStart(n);
621   }
622 }
623
624 // fd read
625 bool handleRead(int fd, IOBufQueue& queue) {
626   for (;;) {
627     auto p = queue.preallocate(100, 65000);
628     ssize_t n = readNoInt(fd, p.first, p.second);
629     if (n == -1 && errno == EAGAIN) {
630       return false;
631     }
632     checkUnixError(n, "read");
633     if (n == 0) {
634       return true;
635     }
636     queue.postallocate(n);
637   }
638 }
639
640 bool discardRead(int fd) {
641   static const size_t bufSize = 65000;
642   // Thread unsafe, but it doesn't matter.
643   static std::unique_ptr<char[]> buf(new char[bufSize]);
644
645   for (;;) {
646     ssize_t n = readNoInt(fd, buf.get(), bufSize);
647     if (n == -1 && errno == EAGAIN) {
648       return false;
649     }
650     checkUnixError(n, "read");
651     if (n == 0) {
652       return true;
653     }
654   }
655 }
656
657 }  // namespace
658
659 std::pair<std::string, std::string> Subprocess::communicate(
660     StringPiece input) {
661   IOBufQueue inputQueue;
662   inputQueue.wrapBuffer(input.data(), input.size());
663
664   auto outQueues = communicateIOBuf(std::move(inputQueue));
665   auto outBufs = std::make_pair(outQueues.first.move(),
666                                 outQueues.second.move());
667   std::pair<std::string, std::string> out;
668   if (outBufs.first) {
669     outBufs.first->coalesce();
670     out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
671                      outBufs.first->length());
672   }
673   if (outBufs.second) {
674     outBufs.second->coalesce();
675     out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
676                      outBufs.second->length());
677   }
678   return out;
679 }
680
681 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
682     IOBufQueue input) {
683   // If the user supplied a non-empty input buffer, make sure
684   // that stdin is a pipe so we can write the data.
685   if (!input.empty()) {
686     // findByChildFd() will throw std::invalid_argument if no pipe for
687     // STDIN_FILENO exists
688     findByChildFd(STDIN_FILENO);
689   }
690
691   std::pair<IOBufQueue, IOBufQueue> out;
692
693   auto readCallback = [&] (int pfd, int cfd) -> bool {
694     if (cfd == STDOUT_FILENO) {
695       return handleRead(pfd, out.first);
696     } else if (cfd == STDERR_FILENO) {
697       return handleRead(pfd, out.second);
698     } else {
699       // Don't close the file descriptor, the child might not like SIGPIPE,
700       // just read and throw the data away.
701       return discardRead(pfd);
702     }
703   };
704
705   auto writeCallback = [&] (int pfd, int cfd) -> bool {
706     if (cfd == STDIN_FILENO) {
707       return handleWrite(pfd, input);
708     } else {
709       // If we don't want to write to this fd, just close it.
710       return true;
711     }
712   };
713
714   communicate(std::move(readCallback), std::move(writeCallback));
715
716   return out;
717 }
718
719 void Subprocess::communicate(FdCallback readCallback,
720                              FdCallback writeCallback) {
721   // This serves to prevent wait() followed by communicate(), but if you
722   // legitimately need that, send a patch to delete this line.
723   returnCode_.enforce(ProcessReturnCode::RUNNING);
724   setAllNonBlocking();
725
726   std::vector<pollfd> fds;
727   fds.reserve(pipes_.size());
728   std::vector<size_t> toClose;  // indexes into pipes_
729   toClose.reserve(pipes_.size());
730
731   while (!pipes_.empty()) {
732     fds.clear();
733     toClose.clear();
734
735     for (auto& p : pipes_) {
736       pollfd pfd;
737       pfd.fd = p.pipe.fd();
738       // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
739       // child's point of view.
740       if (!p.enabled) {
741         // Still keeping fd in watched set so we get notified of POLLHUP /
742         // POLLERR
743         pfd.events = 0;
744       } else if (p.direction == PIPE_IN) {
745         pfd.events = POLLOUT;
746       } else {
747         pfd.events = POLLIN;
748       }
749       fds.push_back(pfd);
750     }
751
752     int r;
753     do {
754       r = ::poll(fds.data(), fds.size(), -1);
755     } while (r == -1 && errno == EINTR);
756     checkUnixError(r, "poll");
757
758     for (size_t i = 0; i < pipes_.size(); ++i) {
759       auto& p = pipes_[i];
760       auto parentFd = p.pipe.fd();
761       DCHECK_EQ(fds[i].fd, parentFd);
762       short events = fds[i].revents;
763
764       bool closed = false;
765       if (events & POLLOUT) {
766         DCHECK(!(events & POLLIN));
767         if (writeCallback(parentFd, p.childFd)) {
768           toClose.push_back(i);
769           closed = true;
770         }
771       }
772
773       // Call read callback on POLLHUP, to give it a chance to read (and act
774       // on) end of file
775       if (events & (POLLIN | POLLHUP)) {
776         DCHECK(!(events & POLLOUT));
777         if (readCallback(parentFd, p.childFd)) {
778           toClose.push_back(i);
779           closed = true;
780         }
781       }
782
783       if ((events & (POLLHUP | POLLERR)) && !closed) {
784         toClose.push_back(i);
785         closed = true;
786       }
787     }
788
789     // Close the fds in reverse order so the indexes hold after erase()
790     for (int idx : boost::adaptors::reverse(toClose)) {
791       auto pos = pipes_.begin() + idx;
792       pos->pipe.close();  // Throws on error
793       pipes_.erase(pos);
794     }
795   }
796 }
797
798 void Subprocess::enableNotifications(int childFd, bool enabled) {
799   pipes_[findByChildFd(childFd)].enabled = enabled;
800 }
801
802 bool Subprocess::notificationsEnabled(int childFd) const {
803   return pipes_[findByChildFd(childFd)].enabled;
804 }
805
806 size_t Subprocess::findByChildFd(int childFd) const {
807   auto pos = std::lower_bound(
808       pipes_.begin(), pipes_.end(), childFd,
809       [] (const Pipe& pipe, int fd) { return pipe.childFd < fd; });
810   if (pos == pipes_.end() || pos->childFd != childFd) {
811     throw std::invalid_argument(folly::to<std::string>(
812         "child fd not found ", childFd));
813   }
814   return pos - pipes_.begin();
815 }
816
817 void Subprocess::closeParentFd(int childFd) {
818   int idx = findByChildFd(childFd);
819   pipes_[idx].pipe.close();  // May throw
820   pipes_.erase(pipes_.begin() + idx);
821 }
822
823 std::vector<Subprocess::ChildPipe> Subprocess::takeOwnershipOfPipes() {
824   std::vector<Subprocess::ChildPipe> pipes;
825   for (auto& p : pipes_) {
826     pipes.emplace_back(p.childFd, std::move(p.pipe));
827   }
828   // release memory
829   std::vector<Pipe>().swap(pipes_);
830   return pipes;
831 }
832
833 namespace {
834
835 class Initializer {
836  public:
837   Initializer() {
838     // We like EPIPE, thanks.
839     ::signal(SIGPIPE, SIG_IGN);
840   }
841 };
842
843 Initializer initializer;
844
845 }  // namespace
846
847 }  // namespace folly