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