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