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