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