2 * Copyright 2014 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include <folly/Subprocess.h>
24 #include <sys/prctl.h>
33 #include <system_error>
35 #include <boost/container/flat_set.hpp>
36 #include <boost/range/adaptors.hpp>
38 #include <glog/logging.h>
40 #include <folly/Conv.h>
41 #include <folly/Exception.h>
42 #include <folly/ScopeGuard.h>
43 #include <folly/String.h>
44 #include <folly/io/Cursor.h>
46 extern char** environ;
48 constexpr int kExecFailure = 127;
49 constexpr int kChildFailure = 126;
53 ProcessReturnCode::State ProcessReturnCode::state() const {
54 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
55 if (rawStatus_ == RV_RUNNING) return RUNNING;
56 if (WIFEXITED(rawStatus_)) return EXITED;
57 if (WIFSIGNALED(rawStatus_)) return KILLED;
58 throw std::runtime_error(to<std::string>(
59 "Invalid ProcessReturnCode: ", rawStatus_));
62 void ProcessReturnCode::enforce(State expected) const {
65 throw std::logic_error(to<std::string>(
66 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
71 int ProcessReturnCode::exitStatus() const {
73 return WEXITSTATUS(rawStatus_);
76 int ProcessReturnCode::killSignal() const {
78 return WTERMSIG(rawStatus_);
81 bool ProcessReturnCode::coreDumped() const {
83 return WCOREDUMP(rawStatus_);
86 std::string ProcessReturnCode::str() const {
93 return to<std::string>("exited with status ", exitStatus());
95 return to<std::string>("killed by signal ", killSignal(),
96 (coreDumped() ? " (core dumped)" : ""));
98 CHECK(false); // unreached
101 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
103 what_(returnCode_.str()) {
106 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
109 : errnoValue_(errnoValue),
110 what_(to<std::string>(errCode == kExecFailure ?
111 "failed to execute " :
112 "error preparing to execute ",
113 executable, ": ", errnoStr(errnoValue))) {
118 // Copy pointers to the given strings in a format suitable for posix_spawn
119 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
120 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
121 for (int i = 0; i < s.size(); i++) {
124 d[s.size()] = nullptr;
128 // Check a wait() status, throw on non-successful
129 void checkStatus(ProcessReturnCode returnCode) {
130 if (returnCode.state() != ProcessReturnCode::EXITED ||
131 returnCode.exitStatus() != 0) {
132 throw CalledProcessError(returnCode);
138 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
139 if (action == Subprocess::PIPE) {
141 action = Subprocess::PIPE_IN;
142 } else if (fd == 1 || fd == 2) {
143 action = Subprocess::PIPE_OUT;
145 throw std::invalid_argument(
146 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
149 fdActions_[fd] = action;
153 Subprocess::Subprocess(
154 const std::vector<std::string>& argv,
155 const Options& options,
156 const char* executable,
157 const std::vector<std::string>* env)
159 returnCode_(RV_NOT_STARTED) {
161 throw std::invalid_argument("argv must not be empty");
163 if (!executable) executable = argv[0].c_str();
164 spawn(cloneStrings(argv), executable, options, env);
167 Subprocess::Subprocess(
168 const std::string& cmd,
169 const Options& options,
170 const std::vector<std::string>* env)
172 returnCode_(RV_NOT_STARTED) {
173 if (options.usePath_) {
174 throw std::invalid_argument("usePath() not allowed when running in shell");
176 const char* shell = getenv("SHELL");
181 std::unique_ptr<const char*[]> argv(new const char*[4]);
184 argv[2] = cmd.c_str();
186 spawn(std::move(argv), shell, options, env);
189 Subprocess::~Subprocess() {
190 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
191 << "Subprocess destroyed without reaping child";
196 void closeChecked(int fd) {
197 checkUnixError(::close(fd), "close");
200 struct ChildErrorInfo {
205 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
206 void childError(int errFd, int errCode, int errnoValue) {
207 ChildErrorInfo info = {errCode, errnoValue};
208 // Write the error information over the pipe to our parent process.
209 // We can't really do anything else if this write call fails.
210 writeNoInt(errFd, &info, sizeof(info));
217 void Subprocess::closeAll() {
218 for (auto& p : pipes_) {
219 closeChecked(p.parentFd);
224 void Subprocess::setAllNonBlocking() {
225 for (auto& p : pipes_) {
227 int flags = ::fcntl(fd, F_GETFL);
228 checkUnixError(flags, "fcntl");
229 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
230 checkUnixError(r, "fcntl");
234 void Subprocess::spawn(
235 std::unique_ptr<const char*[]> argv,
236 const char* executable,
237 const Options& optionsIn,
238 const std::vector<std::string>* env) {
239 if (optionsIn.usePath_ && env) {
240 throw std::invalid_argument(
241 "usePath() not allowed when overriding environment");
244 // Make a copy, we'll mutate options
245 Options options(optionsIn);
247 // On error, close all of the pipes_
248 auto pipesGuard = makeGuard([&] {
249 for (auto& p : this->pipes_) {
250 CHECK_ERR(::close(p.parentFd));
254 // Create a pipe to use to receive error information from the child,
255 // in case it fails before calling exec()
258 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
260 checkUnixError(::pipe(errFds), "pipe");
263 CHECK_ERR(::close(errFds[0]));
264 if (errFds[1] >= 0) {
265 CHECK_ERR(::close(errFds[1]));
269 #if !FOLLY_HAVE_PIPE2
270 // Ask the child to close the read end of the error pipe.
271 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
272 // Set the close-on-exec flag on the write side of the pipe.
273 // This way the pipe will be closed automatically in the child if execve()
274 // succeeds. If the exec fails the child can write error information to the
276 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
279 // Perform the actual work of setting up pipes then forking and
280 // executing the child.
281 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
283 // After spawnInternal() returns the child is alive. We have to be very
284 // careful about throwing after this point. We are inside the constructor,
285 // so if we throw the Subprocess object will have never existed, and the
286 // destructor will never be called.
288 // We should only throw if we got an error via the errFd, and we know the
289 // child has exited and can be immediately waited for. In all other cases,
290 // we have no way of cleaning up the child.
292 // Close writable side of the errFd pipe in the parent process
293 CHECK_ERR(::close(errFds[1]));
296 // Read from the errFd pipe, to tell if the child ran into any errors before
298 readChildErrorPipe(errFds[0], executable);
300 // We have fully succeeded now, so release the guard on pipes_
301 pipesGuard.dismiss();
304 void Subprocess::spawnInternal(
305 std::unique_ptr<const char*[]> argv,
306 const char* executable,
308 const std::vector<std::string>* env,
310 // Parent work, pre-fork: create pipes
311 std::vector<int> childFds;
312 // Close all of the childFds as we leave this scope
314 // These are only pipes, closing them shouldn't fail
315 for (int cfd : childFds) {
316 CHECK_ERR(::close(cfd));
321 for (auto& p : options.fdActions_) {
322 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
324 // We're setting both ends of the pipe as close-on-exec. The child
325 // doesn't need to reset the flag on its end, as we always dup2() the fd,
326 // and dup2() fds don't share the close-on-exec flag.
328 r = ::pipe2(fds, O_CLOEXEC);
329 checkUnixError(r, "pipe2");
332 checkUnixError(r, "pipe");
333 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
334 checkUnixError(r, "set FD_CLOEXEC");
335 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
336 checkUnixError(r, "set FD_CLOEXEC");
339 pinfo.direction = p.second;
341 if (p.second == PIPE_IN) {
342 // Child gets reading end
343 pinfo.parentFd = fds[1];
346 pinfo.parentFd = fds[0];
349 p.second = cfd; // ensure it gets dup2()ed
350 pinfo.childFd = p.first;
351 childFds.push_back(cfd);
352 pipes_.push_back(pinfo);
356 // This should already be sorted, as options.fdActions_ is
357 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
359 // Note that the const casts below are legit, per
360 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
362 char** argVec = const_cast<char**>(argv.get());
364 // Set up environment
365 std::unique_ptr<const char*[]> envHolder;
368 envHolder = cloneStrings(*env);
369 envVec = const_cast<char**>(envHolder.get());
374 // Block all signals around vfork; see http://ewontfix.com/7/.
376 // As the child may run in the same address space as the parent until
377 // the actual execve() system call, any (custom) signal handlers that
378 // the parent has might alter parent's memory if invoked in the child,
379 // with undefined results. So we block all signals in the parent before
380 // vfork(), which will cause them to be blocked in the child as well (we
381 // rely on the fact that Linux, just like all sane implementations, only
382 // clones the calling thread). Then, in the child, we reset all signals
383 // to their default dispositions (while still blocked), and unblock them
384 // (so the exec()ed process inherits the parent's signal mask)
386 // The parent also unblocks all signals as soon as vfork() returns.
388 r = sigfillset(&allBlocked);
389 checkUnixError(r, "sigfillset");
392 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
393 checkPosixError(r, "pthread_sigmask");
395 // Restore signal mask
396 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
397 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
400 // Call c_str() here, as it's not necessarily safe after fork.
401 const char* childDir =
402 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
405 int errnoValue = prepareChild(options, &oldSignals, childDir);
406 if (errnoValue != 0) {
407 childError(errFd, kChildFailure, errnoValue);
410 errnoValue = runChild(executable, argVec, envVec, options);
411 // If we get here, exec() failed.
412 childError(errFd, kExecFailure, errnoValue);
414 // In parent. Make sure vfork() succeeded.
415 checkUnixError(pid, errno, "vfork");
417 // Child is alive. We have to be very careful about throwing after this
418 // point. We are inside the constructor, so if we throw the Subprocess
419 // object will have never existed, and the destructor will never be called.
421 // We should only throw if we got an error via the errFd, and we know the
422 // child has exited and can be immediately waited for. In all other cases,
423 // we have no way of cleaning up the child.
425 returnCode_ = ProcessReturnCode(RV_RUNNING);
428 int Subprocess::prepareChild(const Options& options,
429 const sigset_t* sigmask,
430 const char* childDir) const {
431 // While all signals are blocked, we must reset their
432 // dispositions to default.
433 for (int sig = 1; sig < NSIG; ++sig) {
434 ::signal(sig, SIG_DFL);
438 // Unblock signals; restore signal mask.
439 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
441 return r; // pthread_sigmask() returns an errno value
445 // Change the working directory, if one is given
447 if (::chdir(childDir) == -1) {
452 // We don't have to explicitly close the parent's end of all pipes,
453 // as they all have the FD_CLOEXEC flag set and will be closed at
456 // Close all fds that we're supposed to close.
457 for (auto& p : options.fdActions_) {
458 if (p.second == CLOSE) {
459 if (::close(p.first) == -1) {
462 } else if (p.second != p.first) {
463 if (::dup2(p.second, p.first) == -1) {
469 // If requested, close all other file descriptors. Don't close
470 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
472 if (options.closeOtherFds_) {
473 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
474 if (options.fdActions_.count(fd) == 0) {
481 // Opt to receive signal on parent death, if requested
482 if (options.parentDeathSignal_ != 0) {
483 if (prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0) == -1) {
492 int Subprocess::runChild(const char* executable,
493 char** argv, char** env,
494 const Options& options) const {
495 // Now, finally, exec.
496 if (options.usePath_) {
497 ::execvp(executable, argv);
499 ::execve(executable, argv, env);
504 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
506 auto rc = readNoInt(pfd, &info, sizeof(info));
508 // No data means the child executed successfully, and the pipe
509 // was closed due to the close-on-exec flag being set.
511 } else if (rc != sizeof(ChildErrorInfo)) {
512 // An error occurred trying to read from the pipe, or we got a partial read.
513 // Neither of these cases should really occur in practice.
515 // We can't get any error data from the child in this case, and we don't
516 // know if it is successfully running or not. All we can do is to return
517 // normally, as if the child executed successfully. If something bad
518 // happened the caller should at least get a non-normal exit status from
520 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
521 "rc=" << rc << ", errno=" << errno;
525 // We got error data from the child. The child should exit immediately in
526 // this case, so wait on it to clean up.
529 // Throw to signal the error
530 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
533 ProcessReturnCode Subprocess::poll() {
534 returnCode_.enforce(ProcessReturnCode::RUNNING);
537 pid_t found = ::waitpid(pid_, &status, WNOHANG);
538 checkUnixError(found, "waitpid");
540 returnCode_ = ProcessReturnCode(status);
546 bool Subprocess::pollChecked() {
547 if (poll().state() == ProcessReturnCode::RUNNING) {
550 checkStatus(returnCode_);
554 ProcessReturnCode Subprocess::wait() {
555 returnCode_.enforce(ProcessReturnCode::RUNNING);
560 found = ::waitpid(pid_, &status, 0);
561 } while (found == -1 && errno == EINTR);
562 checkUnixError(found, "waitpid");
563 DCHECK_EQ(found, pid_);
564 returnCode_ = ProcessReturnCode(status);
569 void Subprocess::waitChecked() {
571 checkStatus(returnCode_);
574 void Subprocess::sendSignal(int signal) {
575 returnCode_.enforce(ProcessReturnCode::RUNNING);
576 int r = ::kill(pid_, signal);
577 checkUnixError(r, "kill");
580 pid_t Subprocess::pid() const {
586 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
587 auto* p = queue.front();
588 if (!p) return std::make_pair(nullptr, 0);
589 return io::Cursor(p).peek();
593 bool handleWrite(int fd, IOBufQueue& queue) {
595 auto p = queueFront(queue);
600 ssize_t n = writeNoInt(fd, p.first, p.second);
601 if (n == -1 && errno == EAGAIN) {
604 checkUnixError(n, "write");
610 bool handleRead(int fd, IOBufQueue& queue) {
612 auto p = queue.preallocate(100, 65000);
613 ssize_t n = readNoInt(fd, p.first, p.second);
614 if (n == -1 && errno == EAGAIN) {
617 checkUnixError(n, "read");
621 queue.postallocate(n);
625 bool discardRead(int fd) {
626 static const size_t bufSize = 65000;
627 // Thread unsafe, but it doesn't matter.
628 static std::unique_ptr<char[]> buf(new char[bufSize]);
631 ssize_t n = readNoInt(fd, buf.get(), bufSize);
632 if (n == -1 && errno == EAGAIN) {
635 checkUnixError(n, "read");
644 std::pair<std::string, std::string> Subprocess::communicate(
646 IOBufQueue inputQueue;
647 inputQueue.wrapBuffer(input.data(), input.size());
649 auto outQueues = communicateIOBuf(std::move(inputQueue));
650 auto outBufs = std::make_pair(outQueues.first.move(),
651 outQueues.second.move());
652 std::pair<std::string, std::string> out;
654 outBufs.first->coalesce();
655 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
656 outBufs.first->length());
658 if (outBufs.second) {
659 outBufs.second->coalesce();
660 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
661 outBufs.second->length());
666 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
668 // If the user supplied a non-empty input buffer, make sure
669 // that stdin is a pipe so we can write the data.
670 if (!input.empty()) {
671 // findByChildFd() will throw std::invalid_argument if no pipe for
672 // STDIN_FILENO exists
673 findByChildFd(STDIN_FILENO);
676 std::pair<IOBufQueue, IOBufQueue> out;
678 auto readCallback = [&] (int pfd, int cfd) -> bool {
679 if (cfd == STDOUT_FILENO) {
680 return handleRead(pfd, out.first);
681 } else if (cfd == STDERR_FILENO) {
682 return handleRead(pfd, out.second);
684 // Don't close the file descriptor, the child might not like SIGPIPE,
685 // just read and throw the data away.
686 return discardRead(pfd);
690 auto writeCallback = [&] (int pfd, int cfd) -> bool {
691 if (cfd == STDIN_FILENO) {
692 return handleWrite(pfd, input);
694 // If we don't want to write to this fd, just close it.
699 communicate(std::move(readCallback), std::move(writeCallback));
704 void Subprocess::communicate(FdCallback readCallback,
705 FdCallback writeCallback) {
706 returnCode_.enforce(ProcessReturnCode::RUNNING);
709 std::vector<pollfd> fds;
710 fds.reserve(pipes_.size());
711 std::vector<int> toClose;
712 toClose.reserve(pipes_.size());
714 while (!pipes_.empty()) {
718 for (auto& p : pipes_) {
721 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
722 // child's point of view.
724 // Still keeping fd in watched set so we get notified of POLLHUP /
727 } else if (p.direction == PIPE_IN) {
728 pfd.events = POLLOUT;
737 r = ::poll(fds.data(), fds.size(), -1);
738 } while (r == -1 && errno == EINTR);
739 checkUnixError(r, "poll");
741 for (int i = 0; i < pipes_.size(); ++i) {
743 DCHECK_EQ(fds[i].fd, p.parentFd);
744 short events = fds[i].revents;
747 if (events & POLLOUT) {
748 DCHECK(!(events & POLLIN));
749 if (writeCallback(p.parentFd, p.childFd)) {
750 toClose.push_back(i);
755 // Call read callback on POLLHUP, to give it a chance to read (and act
757 if (events & (POLLIN | POLLHUP)) {
758 DCHECK(!(events & POLLOUT));
759 if (readCallback(p.parentFd, p.childFd)) {
760 toClose.push_back(i);
765 if ((events & (POLLHUP | POLLERR)) && !closed) {
766 toClose.push_back(i);
771 // Close the fds in reverse order so the indexes hold after erase()
772 for (int idx : boost::adaptors::reverse(toClose)) {
773 auto pos = pipes_.begin() + idx;
774 closeChecked(pos->parentFd);
780 void Subprocess::enableNotifications(int childFd, bool enabled) {
781 pipes_[findByChildFd(childFd)].enabled = enabled;
784 bool Subprocess::notificationsEnabled(int childFd) const {
785 return pipes_[findByChildFd(childFd)].enabled;
788 int Subprocess::findByChildFd(int childFd) const {
789 auto pos = std::lower_bound(
790 pipes_.begin(), pipes_.end(), childFd,
791 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
792 if (pos == pipes_.end() || pos->childFd != childFd) {
793 throw std::invalid_argument(folly::to<std::string>(
794 "child fd not found ", childFd));
796 return pos - pipes_.begin();
799 void Subprocess::closeParentFd(int childFd) {
800 int idx = findByChildFd(childFd);
801 closeChecked(pipes_[idx].parentFd);
802 pipes_.erase(pipes_.begin() + idx);
810 // We like EPIPE, thanks.
811 ::signal(SIGPIPE, SIG_IGN);
815 Initializer initializer;