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