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