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