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/FileUtil.h>
43 #include <folly/ScopeGuard.h>
44 #include <folly/String.h>
45 #include <folly/io/Cursor.h>
47 extern char** environ;
49 constexpr int kExecFailure = 127;
50 constexpr int kChildFailure = 126;
54 ProcessReturnCode::State ProcessReturnCode::state() const {
55 if (rawStatus_ == RV_NOT_STARTED) return NOT_STARTED;
56 if (rawStatus_ == RV_RUNNING) return RUNNING;
57 if (WIFEXITED(rawStatus_)) return EXITED;
58 if (WIFSIGNALED(rawStatus_)) return KILLED;
59 throw std::runtime_error(to<std::string>(
60 "Invalid ProcessReturnCode: ", rawStatus_));
63 void ProcessReturnCode::enforce(State expected) const {
66 throw std::logic_error(to<std::string>(
67 "Bad use of ProcessReturnCode; state is ", s, " expected ", expected
72 int ProcessReturnCode::exitStatus() const {
74 return WEXITSTATUS(rawStatus_);
77 int ProcessReturnCode::killSignal() const {
79 return WTERMSIG(rawStatus_);
82 bool ProcessReturnCode::coreDumped() const {
84 return WCOREDUMP(rawStatus_);
87 std::string ProcessReturnCode::str() const {
94 return to<std::string>("exited with status ", exitStatus());
96 return to<std::string>("killed by signal ", killSignal(),
97 (coreDumped() ? " (core dumped)" : ""));
99 CHECK(false); // unreached
102 CalledProcessError::CalledProcessError(ProcessReturnCode rc)
104 what_(returnCode_.str()) {
107 SubprocessSpawnError::SubprocessSpawnError(const char* executable,
110 : errnoValue_(errnoValue),
111 what_(to<std::string>(errCode == kExecFailure ?
112 "failed to execute " :
113 "error preparing to execute ",
114 executable, ": ", errnoStr(errnoValue))) {
119 // Copy pointers to the given strings in a format suitable for posix_spawn
120 std::unique_ptr<const char*[]> cloneStrings(const std::vector<std::string>& s) {
121 std::unique_ptr<const char*[]> d(new const char*[s.size() + 1]);
122 for (int i = 0; i < s.size(); i++) {
125 d[s.size()] = nullptr;
129 // Check a wait() status, throw on non-successful
130 void checkStatus(ProcessReturnCode returnCode) {
131 if (returnCode.state() != ProcessReturnCode::EXITED ||
132 returnCode.exitStatus() != 0) {
133 throw CalledProcessError(returnCode);
139 Subprocess::Options& Subprocess::Options::fd(int fd, int action) {
140 if (action == Subprocess::PIPE) {
142 action = Subprocess::PIPE_IN;
143 } else if (fd == 1 || fd == 2) {
144 action = Subprocess::PIPE_OUT;
146 throw std::invalid_argument(
147 to<std::string>("Only fds 0, 1, 2 are valid for action=PIPE: ", fd));
150 fdActions_[fd] = action;
154 Subprocess::Subprocess(
155 const std::vector<std::string>& argv,
156 const Options& options,
157 const char* executable,
158 const std::vector<std::string>* env)
160 returnCode_(RV_NOT_STARTED) {
162 throw std::invalid_argument("argv must not be empty");
164 if (!executable) executable = argv[0].c_str();
165 spawn(cloneStrings(argv), executable, options, env);
168 Subprocess::Subprocess(
169 const std::string& cmd,
170 const Options& options,
171 const std::vector<std::string>* env)
173 returnCode_(RV_NOT_STARTED) {
174 if (options.usePath_) {
175 throw std::invalid_argument("usePath() not allowed when running in shell");
177 const char* shell = getenv("SHELL");
182 std::unique_ptr<const char*[]> argv(new const char*[4]);
185 argv[2] = cmd.c_str();
187 spawn(std::move(argv), shell, options, env);
190 Subprocess::~Subprocess() {
191 CHECK_NE(returnCode_.state(), ProcessReturnCode::RUNNING)
192 << "Subprocess destroyed without reaping child";
197 void closeChecked(int fd) {
198 checkUnixError(::close(fd), "close");
201 struct ChildErrorInfo {
206 FOLLY_NORETURN void childError(int errFd, int errCode, int errnoValue);
207 void childError(int errFd, int errCode, int errnoValue) {
208 ChildErrorInfo info = {errCode, errnoValue};
209 // Write the error information over the pipe to our parent process.
210 // We can't really do anything else if this write call fails.
211 writeNoInt(errFd, &info, sizeof(info));
218 void Subprocess::closeAll() {
219 for (auto& p : pipes_) {
220 closeChecked(p.parentFd);
225 void Subprocess::setAllNonBlocking() {
226 for (auto& p : pipes_) {
228 int flags = ::fcntl(fd, F_GETFL);
229 checkUnixError(flags, "fcntl");
230 int r = ::fcntl(fd, F_SETFL, flags | O_NONBLOCK);
231 checkUnixError(r, "fcntl");
235 void Subprocess::spawn(
236 std::unique_ptr<const char*[]> argv,
237 const char* executable,
238 const Options& optionsIn,
239 const std::vector<std::string>* env) {
240 if (optionsIn.usePath_ && env) {
241 throw std::invalid_argument(
242 "usePath() not allowed when overriding environment");
245 // Make a copy, we'll mutate options
246 Options options(optionsIn);
248 // On error, close all of the pipes_
249 auto pipesGuard = makeGuard([&] {
250 for (auto& p : this->pipes_) {
251 CHECK_ERR(::close(p.parentFd));
255 // Create a pipe to use to receive error information from the child,
256 // in case it fails before calling exec()
259 checkUnixError(::pipe2(errFds, O_CLOEXEC), "pipe2");
261 checkUnixError(::pipe(errFds), "pipe");
264 CHECK_ERR(::close(errFds[0]));
265 if (errFds[1] >= 0) {
266 CHECK_ERR(::close(errFds[1]));
270 #if !FOLLY_HAVE_PIPE2
271 // Ask the child to close the read end of the error pipe.
272 checkUnixError(fcntl(errFds[0], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
273 // Set the close-on-exec flag on the write side of the pipe.
274 // This way the pipe will be closed automatically in the child if execve()
275 // succeeds. If the exec fails the child can write error information to the
277 checkUnixError(fcntl(errFds[1], F_SETFD, FD_CLOEXEC), "set FD_CLOEXEC");
280 // Perform the actual work of setting up pipes then forking and
281 // executing the child.
282 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
284 // After spawnInternal() returns the child is alive. We have to be very
285 // careful about throwing after this point. We are inside the constructor,
286 // so if we throw the Subprocess object will have never existed, and the
287 // destructor will never be called.
289 // We should only throw if we got an error via the errFd, and we know the
290 // child has exited and can be immediately waited for. In all other cases,
291 // we have no way of cleaning up the child.
293 // Close writable side of the errFd pipe in the parent process
294 CHECK_ERR(::close(errFds[1]));
297 // Read from the errFd pipe, to tell if the child ran into any errors before
299 readChildErrorPipe(errFds[0], executable);
301 // We have fully succeeded now, so release the guard on pipes_
302 pipesGuard.dismiss();
305 void Subprocess::spawnInternal(
306 std::unique_ptr<const char*[]> argv,
307 const char* executable,
309 const std::vector<std::string>* env,
311 // Parent work, pre-fork: create pipes
312 std::vector<int> childFds;
313 // Close all of the childFds as we leave this scope
315 // These are only pipes, closing them shouldn't fail
316 for (int cfd : childFds) {
317 CHECK_ERR(::close(cfd));
322 for (auto& p : options.fdActions_) {
323 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
325 // We're setting both ends of the pipe as close-on-exec. The child
326 // doesn't need to reset the flag on its end, as we always dup2() the fd,
327 // and dup2() fds don't share the close-on-exec flag.
329 r = ::pipe2(fds, O_CLOEXEC);
330 checkUnixError(r, "pipe2");
333 checkUnixError(r, "pipe");
334 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
335 checkUnixError(r, "set FD_CLOEXEC");
336 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
337 checkUnixError(r, "set FD_CLOEXEC");
340 pinfo.direction = p.second;
342 if (p.second == PIPE_IN) {
343 // Child gets reading end
344 pinfo.parentFd = fds[1];
347 pinfo.parentFd = fds[0];
350 p.second = cfd; // ensure it gets dup2()ed
351 pinfo.childFd = p.first;
352 childFds.push_back(cfd);
353 pipes_.push_back(pinfo);
357 // This should already be sorted, as options.fdActions_ is
358 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
360 // Note that the const casts below are legit, per
361 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
363 char** argVec = const_cast<char**>(argv.get());
365 // Set up environment
366 std::unique_ptr<const char*[]> envHolder;
369 envHolder = cloneStrings(*env);
370 envVec = const_cast<char**>(envHolder.get());
375 // Block all signals around vfork; see http://ewontfix.com/7/.
377 // As the child may run in the same address space as the parent until
378 // the actual execve() system call, any (custom) signal handlers that
379 // the parent has might alter parent's memory if invoked in the child,
380 // with undefined results. So we block all signals in the parent before
381 // vfork(), which will cause them to be blocked in the child as well (we
382 // rely on the fact that Linux, just like all sane implementations, only
383 // clones the calling thread). Then, in the child, we reset all signals
384 // to their default dispositions (while still blocked), and unblock them
385 // (so the exec()ed process inherits the parent's signal mask)
387 // The parent also unblocks all signals as soon as vfork() returns.
389 r = sigfillset(&allBlocked);
390 checkUnixError(r, "sigfillset");
393 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
394 checkPosixError(r, "pthread_sigmask");
396 // Restore signal mask
397 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
398 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
401 // Call c_str() here, as it's not necessarily safe after fork.
402 const char* childDir =
403 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
406 int errnoValue = prepareChild(options, &oldSignals, childDir);
407 if (errnoValue != 0) {
408 childError(errFd, kChildFailure, errnoValue);
411 errnoValue = runChild(executable, argVec, envVec, options);
412 // If we get here, exec() failed.
413 childError(errFd, kExecFailure, errnoValue);
415 // In parent. Make sure vfork() succeeded.
416 checkUnixError(pid, errno, "vfork");
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.
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.
426 returnCode_ = ProcessReturnCode(RV_RUNNING);
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);
439 // Unblock signals; restore signal mask.
440 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
442 return r; // pthread_sigmask() returns an errno value
446 // Change the working directory, if one is given
448 if (::chdir(childDir) == -1) {
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
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) {
463 } else if (p.second != p.first) {
464 if (::dup2(p.second, p.first) == -1) {
470 // If requested, close all other file descriptors. Don't close
471 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
473 if (options.closeOtherFds_) {
474 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
475 if (options.fdActions_.count(fd) == 0) {
482 // Opt to receive signal on parent death, if requested
483 if (options.parentDeathSignal_ != 0) {
484 if (prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0) == -1) {
493 int Subprocess::runChild(const char* executable,
494 char** argv, char** env,
495 const Options& options) const {
496 // Now, finally, exec.
498 if (options.usePath_) {
499 ::execvp(executable, argv);
501 ::execve(executable, argv, env);
506 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
508 auto rc = readNoInt(pfd, &info, sizeof(info));
510 // No data means the child executed successfully, and the pipe
511 // was closed due to the close-on-exec flag being set.
513 } else if (rc != sizeof(ChildErrorInfo)) {
514 // An error occurred trying to read from the pipe, or we got a partial read.
515 // Neither of these cases should really occur in practice.
517 // We can't get any error data from the child in this case, and we don't
518 // know if it is successfully running or not. All we can do is to return
519 // normally, as if the child executed successfully. If something bad
520 // happened the caller should at least get a non-normal exit status from
522 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
523 "rc=" << rc << ", errno=" << errno;
527 // We got error data from the child. The child should exit immediately in
528 // this case, so wait on it to clean up.
531 // Throw to signal the error
532 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
535 ProcessReturnCode Subprocess::poll() {
536 returnCode_.enforce(ProcessReturnCode::RUNNING);
539 pid_t found = ::waitpid(pid_, &status, WNOHANG);
540 checkUnixError(found, "waitpid");
542 returnCode_ = ProcessReturnCode(status);
548 bool Subprocess::pollChecked() {
549 if (poll().state() == ProcessReturnCode::RUNNING) {
552 checkStatus(returnCode_);
556 ProcessReturnCode Subprocess::wait() {
557 returnCode_.enforce(ProcessReturnCode::RUNNING);
562 found = ::waitpid(pid_, &status, 0);
563 } while (found == -1 && errno == EINTR);
564 checkUnixError(found, "waitpid");
565 DCHECK_EQ(found, pid_);
566 returnCode_ = ProcessReturnCode(status);
571 void Subprocess::waitChecked() {
573 checkStatus(returnCode_);
576 void Subprocess::sendSignal(int signal) {
577 returnCode_.enforce(ProcessReturnCode::RUNNING);
578 int r = ::kill(pid_, signal);
579 checkUnixError(r, "kill");
582 pid_t Subprocess::pid() const {
588 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
589 auto* p = queue.front();
590 if (!p) return std::make_pair(nullptr, 0);
591 return io::Cursor(p).peek();
595 bool handleWrite(int fd, IOBufQueue& queue) {
597 auto p = queueFront(queue);
602 ssize_t n = writeNoInt(fd, p.first, p.second);
603 if (n == -1 && errno == EAGAIN) {
606 checkUnixError(n, "write");
612 bool handleRead(int fd, IOBufQueue& queue) {
614 auto p = queue.preallocate(100, 65000);
615 ssize_t n = readNoInt(fd, p.first, p.second);
616 if (n == -1 && errno == EAGAIN) {
619 checkUnixError(n, "read");
623 queue.postallocate(n);
627 bool discardRead(int fd) {
628 static const size_t bufSize = 65000;
629 // Thread unsafe, but it doesn't matter.
630 static std::unique_ptr<char[]> buf(new char[bufSize]);
633 ssize_t n = readNoInt(fd, buf.get(), bufSize);
634 if (n == -1 && errno == EAGAIN) {
637 checkUnixError(n, "read");
646 std::pair<std::string, std::string> Subprocess::communicate(
648 IOBufQueue inputQueue;
649 inputQueue.wrapBuffer(input.data(), input.size());
651 auto outQueues = communicateIOBuf(std::move(inputQueue));
652 auto outBufs = std::make_pair(outQueues.first.move(),
653 outQueues.second.move());
654 std::pair<std::string, std::string> out;
656 outBufs.first->coalesce();
657 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
658 outBufs.first->length());
660 if (outBufs.second) {
661 outBufs.second->coalesce();
662 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
663 outBufs.second->length());
668 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
670 // If the user supplied a non-empty input buffer, make sure
671 // that stdin is a pipe so we can write the data.
672 if (!input.empty()) {
673 // findByChildFd() will throw std::invalid_argument if no pipe for
674 // STDIN_FILENO exists
675 findByChildFd(STDIN_FILENO);
678 std::pair<IOBufQueue, IOBufQueue> out;
680 auto readCallback = [&] (int pfd, int cfd) -> bool {
681 if (cfd == STDOUT_FILENO) {
682 return handleRead(pfd, out.first);
683 } else if (cfd == STDERR_FILENO) {
684 return handleRead(pfd, out.second);
686 // Don't close the file descriptor, the child might not like SIGPIPE,
687 // just read and throw the data away.
688 return discardRead(pfd);
692 auto writeCallback = [&] (int pfd, int cfd) -> bool {
693 if (cfd == STDIN_FILENO) {
694 return handleWrite(pfd, input);
696 // If we don't want to write to this fd, just close it.
701 communicate(std::move(readCallback), std::move(writeCallback));
706 void Subprocess::communicate(FdCallback readCallback,
707 FdCallback writeCallback) {
708 returnCode_.enforce(ProcessReturnCode::RUNNING);
711 std::vector<pollfd> fds;
712 fds.reserve(pipes_.size());
713 std::vector<int> toClose;
714 toClose.reserve(pipes_.size());
716 while (!pipes_.empty()) {
720 for (auto& p : pipes_) {
723 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
724 // child's point of view.
726 // Still keeping fd in watched set so we get notified of POLLHUP /
729 } else if (p.direction == PIPE_IN) {
730 pfd.events = POLLOUT;
739 r = ::poll(fds.data(), fds.size(), -1);
740 } while (r == -1 && errno == EINTR);
741 checkUnixError(r, "poll");
743 for (int i = 0; i < pipes_.size(); ++i) {
745 DCHECK_EQ(fds[i].fd, p.parentFd);
746 short events = fds[i].revents;
749 if (events & POLLOUT) {
750 DCHECK(!(events & POLLIN));
751 if (writeCallback(p.parentFd, p.childFd)) {
752 toClose.push_back(i);
757 // Call read callback on POLLHUP, to give it a chance to read (and act
759 if (events & (POLLIN | POLLHUP)) {
760 DCHECK(!(events & POLLOUT));
761 if (readCallback(p.parentFd, p.childFd)) {
762 toClose.push_back(i);
767 if ((events & (POLLHUP | POLLERR)) && !closed) {
768 toClose.push_back(i);
773 // Close the fds in reverse order so the indexes hold after erase()
774 for (int idx : boost::adaptors::reverse(toClose)) {
775 auto pos = pipes_.begin() + idx;
776 closeChecked(pos->parentFd);
782 void Subprocess::enableNotifications(int childFd, bool enabled) {
783 pipes_[findByChildFd(childFd)].enabled = enabled;
786 bool Subprocess::notificationsEnabled(int childFd) const {
787 return pipes_[findByChildFd(childFd)].enabled;
790 int Subprocess::findByChildFd(int childFd) const {
791 auto pos = std::lower_bound(
792 pipes_.begin(), pipes_.end(), childFd,
793 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
794 if (pos == pipes_.end() || pos->childFd != childFd) {
795 throw std::invalid_argument(folly::to<std::string>(
796 "child fd not found ", childFd));
798 return pos - pipes_.begin();
801 void Subprocess::closeParentFd(int childFd) {
802 int idx = findByChildFd(childFd);
803 closeChecked(pipes_[idx].parentFd);
804 pipes_.erase(pipes_.begin() + idx);
812 // We like EPIPE, thanks.
813 ::signal(SIGPIPE, SIG_IGN);
817 Initializer initializer;