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 int r = ::pipe2(errFds, O_CLOEXEC);
261 int r = ::pipe(errFds);
263 checkUnixError(r, "pipe");
265 CHECK_ERR(::close(errFds[0]));
266 if (errFds[1] >= 0) {
267 CHECK_ERR(::close(errFds[1]));
270 // Ask the child to close the read end of the error pipe.
271 options.fdActions_[errFds[0]] = CLOSE;
273 #if !FOLLY_HAVE_PIPE2
274 r = fcntl(errFds[0], F_SETFD, FD_CLOEXEC);
275 checkUnixError(r, "set FD_CLOEXEC");
276 // Set the close-on-exec flag on the write side of the pipe.
277 // This way the pipe will be closed automatically in the child if execve()
278 // succeeds. If the exec fails the child can write error information to the
280 r = fcntl(errFds[1], F_SETFD, FD_CLOEXEC);
281 checkUnixError(r, "set FD_CLOEXEC");
284 // Perform the actual work of setting up pipes then forking and
285 // executing the child.
286 spawnInternal(std::move(argv), executable, options, env, errFds[1]);
288 // After spawnInternal() returns the child is alive. We have to be very
289 // careful about throwing after this point. We are inside the constructor,
290 // so if we throw the Subprocess object will have never existed, and the
291 // destructor will never be called.
293 // We should only throw if we got an error via the errFd, and we know the
294 // child has exited and can be immediately waited for. In all other cases,
295 // we have no way of cleaning up the child.
297 // Close writable side of the errFd pipe in the parent process
298 CHECK_ERR(::close(errFds[1]));
301 // Read from the errFd pipe, to tell if the child ran into any errors before
303 readChildErrorPipe(errFds[0], executable);
305 // We have fully succeeded now, so release the guard on pipes_
306 pipesGuard.dismiss();
309 void Subprocess::spawnInternal(
310 std::unique_ptr<const char*[]> argv,
311 const char* executable,
313 const std::vector<std::string>* env,
315 // Parent work, pre-fork: create pipes
316 std::vector<int> childFds;
317 // Close all of the childFds as we leave this scope
319 // These are only pipes, closing them shouldn't fail
320 for (int cfd : childFds) {
321 CHECK_ERR(::close(cfd));
326 for (auto& p : options.fdActions_) {
327 if (p.second == PIPE_IN || p.second == PIPE_OUT) {
329 // We're setting both ends of the pipe as close-on-exec. The child
330 // doesn't need to reset the flag on its end, as we always dup2() the fd,
331 // and dup2() fds don't share the close-on-exec flag.
333 r = ::pipe2(fds, O_CLOEXEC);
334 checkUnixError(r, "pipe2");
337 checkUnixError(r, "pipe");
338 r = fcntl(fds[0], F_SETFD, FD_CLOEXEC);
339 checkUnixError(r, "set FD_CLOEXEC");
340 r = fcntl(fds[1], F_SETFD, FD_CLOEXEC);
341 checkUnixError(r, "set FD_CLOEXEC");
344 pinfo.direction = p.second;
346 if (p.second == PIPE_IN) {
347 // Child gets reading end
348 pinfo.parentFd = fds[1];
351 pinfo.parentFd = fds[0];
354 p.second = cfd; // ensure it gets dup2()ed
355 pinfo.childFd = p.first;
356 childFds.push_back(cfd);
357 pipes_.push_back(pinfo);
361 // This should already be sorted, as options.fdActions_ is
362 DCHECK(std::is_sorted(pipes_.begin(), pipes_.end()));
364 // Note that the const casts below are legit, per
365 // http://pubs.opengroup.org/onlinepubs/009695399/functions/exec.html
367 char** argVec = const_cast<char**>(argv.get());
369 // Set up environment
370 std::unique_ptr<const char*[]> envHolder;
373 envHolder = cloneStrings(*env);
374 envVec = const_cast<char**>(envHolder.get());
379 // Block all signals around vfork; see http://ewontfix.com/7/.
381 // As the child may run in the same address space as the parent until
382 // the actual execve() system call, any (custom) signal handlers that
383 // the parent has might alter parent's memory if invoked in the child,
384 // with undefined results. So we block all signals in the parent before
385 // vfork(), which will cause them to be blocked in the child as well (we
386 // rely on the fact that Linux, just like all sane implementations, only
387 // clones the calling thread). Then, in the child, we reset all signals
388 // to their default dispositions (while still blocked), and unblock them
389 // (so the exec()ed process inherits the parent's signal mask)
391 // The parent also unblocks all signals as soon as vfork() returns.
393 r = sigfillset(&allBlocked);
394 checkUnixError(r, "sigfillset");
397 r = pthread_sigmask(SIG_SETMASK, &allBlocked, &oldSignals);
398 checkPosixError(r, "pthread_sigmask");
400 // Restore signal mask
401 r = pthread_sigmask(SIG_SETMASK, &oldSignals, nullptr);
402 CHECK_EQ(r, 0) << "pthread_sigmask: " << errnoStr(r); // shouldn't fail
405 // Call c_str() here, as it's not necessarily safe after fork.
406 const char* childDir =
407 options.childDir_.empty() ? nullptr : options.childDir_.c_str();
410 int errnoValue = prepareChild(options, &oldSignals, childDir);
411 if (errnoValue != 0) {
412 childError(errFd, kChildFailure, errnoValue);
415 errnoValue = runChild(executable, argVec, envVec, options);
416 // If we get here, exec() failed.
417 childError(errFd, kExecFailure, errnoValue);
419 // In parent. Make sure vfork() succeeded.
420 checkUnixError(pid, errno, "vfork");
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.
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.
430 returnCode_ = ProcessReturnCode(RV_RUNNING);
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);
443 // Unblock signals; restore signal mask.
444 int r = pthread_sigmask(SIG_SETMASK, sigmask, nullptr);
446 return r; // pthread_sigmask() returns an errno value
450 // Change the working directory, if one is given
452 if (::chdir(childDir) == -1) {
457 // Close parent's ends of all pipes
458 for (auto& p : pipes_) {
459 if (::close(p.parentFd) == -1) {
464 // Close all fds that we're supposed to close.
465 for (auto& p : options.fdActions_) {
466 if (p.second == CLOSE) {
467 if (::close(p.first) == -1) {
470 } else if (p.second != p.first) {
471 if (::dup2(p.second, p.first) == -1) {
477 // If requested, close all other file descriptors. Don't close
478 // any fds in options.fdActions_, and don't touch stdin, stdout, stderr.
480 if (options.closeOtherFds_) {
481 for (int fd = getdtablesize() - 1; fd >= 3; --fd) {
482 if (options.fdActions_.count(fd) == 0) {
489 // Opt to receive signal on parent death, if requested
490 if (options.parentDeathSignal_ != 0) {
491 if (prctl(PR_SET_PDEATHSIG, options.parentDeathSignal_, 0, 0, 0) == -1) {
500 int Subprocess::runChild(const char* executable,
501 char** argv, char** env,
502 const Options& options) const {
503 // Now, finally, exec.
505 if (options.usePath_) {
506 ::execvp(executable, argv);
508 ::execve(executable, argv, env);
513 void Subprocess::readChildErrorPipe(int pfd, const char* executable) {
515 auto rc = readNoInt(pfd, &info, sizeof(info));
517 // No data means the child executed successfully, and the pipe
518 // was closed due to the close-on-exec flag being set.
520 } else if (rc != sizeof(ChildErrorInfo)) {
521 // An error occurred trying to read from the pipe, or we got a partial read.
522 // Neither of these cases should really occur in practice.
524 // We can't get any error data from the child in this case, and we don't
525 // know if it is successfully running or not. All we can do is to return
526 // normally, as if the child executed successfully. If something bad
527 // happened the caller should at least get a non-normal exit status from
529 LOG(ERROR) << "unexpected error trying to read from child error pipe " <<
530 "rc=" << rc << ", errno=" << errno;
534 // We got error data from the child. The child should exit immediately in
535 // this case, so wait on it to clean up.
538 // Throw to signal the error
539 throw SubprocessSpawnError(executable, info.errCode, info.errnoValue);
542 ProcessReturnCode Subprocess::poll() {
543 returnCode_.enforce(ProcessReturnCode::RUNNING);
546 pid_t found = ::waitpid(pid_, &status, WNOHANG);
547 checkUnixError(found, "waitpid");
549 returnCode_ = ProcessReturnCode(status);
555 bool Subprocess::pollChecked() {
556 if (poll().state() == ProcessReturnCode::RUNNING) {
559 checkStatus(returnCode_);
563 ProcessReturnCode Subprocess::wait() {
564 returnCode_.enforce(ProcessReturnCode::RUNNING);
569 found = ::waitpid(pid_, &status, 0);
570 } while (found == -1 && errno == EINTR);
571 checkUnixError(found, "waitpid");
572 DCHECK_EQ(found, pid_);
573 returnCode_ = ProcessReturnCode(status);
578 void Subprocess::waitChecked() {
580 checkStatus(returnCode_);
583 void Subprocess::sendSignal(int signal) {
584 returnCode_.enforce(ProcessReturnCode::RUNNING);
585 int r = ::kill(pid_, signal);
586 checkUnixError(r, "kill");
589 pid_t Subprocess::pid() const {
595 std::pair<const uint8_t*, size_t> queueFront(const IOBufQueue& queue) {
596 auto* p = queue.front();
597 if (!p) return std::make_pair(nullptr, 0);
598 return io::Cursor(p).peek();
602 bool handleWrite(int fd, IOBufQueue& queue) {
604 auto p = queueFront(queue);
609 ssize_t n = writeNoInt(fd, p.first, p.second);
610 if (n == -1 && errno == EAGAIN) {
613 checkUnixError(n, "write");
619 bool handleRead(int fd, IOBufQueue& queue) {
621 auto p = queue.preallocate(100, 65000);
622 ssize_t n = readNoInt(fd, p.first, p.second);
623 if (n == -1 && errno == EAGAIN) {
626 checkUnixError(n, "read");
630 queue.postallocate(n);
634 bool discardRead(int fd) {
635 static const size_t bufSize = 65000;
636 // Thread unsafe, but it doesn't matter.
637 static std::unique_ptr<char[]> buf(new char[bufSize]);
640 ssize_t n = readNoInt(fd, buf.get(), bufSize);
641 if (n == -1 && errno == EAGAIN) {
644 checkUnixError(n, "read");
653 std::pair<std::string, std::string> Subprocess::communicate(
655 IOBufQueue inputQueue;
656 inputQueue.wrapBuffer(input.data(), input.size());
658 auto outQueues = communicateIOBuf(std::move(inputQueue));
659 auto outBufs = std::make_pair(outQueues.first.move(),
660 outQueues.second.move());
661 std::pair<std::string, std::string> out;
663 outBufs.first->coalesce();
664 out.first.assign(reinterpret_cast<const char*>(outBufs.first->data()),
665 outBufs.first->length());
667 if (outBufs.second) {
668 outBufs.second->coalesce();
669 out.second.assign(reinterpret_cast<const char*>(outBufs.second->data()),
670 outBufs.second->length());
675 std::pair<IOBufQueue, IOBufQueue> Subprocess::communicateIOBuf(
677 // If the user supplied a non-empty input buffer, make sure
678 // that stdin is a pipe so we can write the data.
679 if (!input.empty()) {
680 // findByChildFd() will throw std::invalid_argument if no pipe for
681 // STDIN_FILENO exists
682 findByChildFd(STDIN_FILENO);
685 std::pair<IOBufQueue, IOBufQueue> out;
687 auto readCallback = [&] (int pfd, int cfd) -> bool {
688 if (cfd == STDOUT_FILENO) {
689 return handleRead(pfd, out.first);
690 } else if (cfd == STDERR_FILENO) {
691 return handleRead(pfd, out.second);
693 // Don't close the file descriptor, the child might not like SIGPIPE,
694 // just read and throw the data away.
695 return discardRead(pfd);
699 auto writeCallback = [&] (int pfd, int cfd) -> bool {
700 if (cfd == STDIN_FILENO) {
701 return handleWrite(pfd, input);
703 // If we don't want to write to this fd, just close it.
708 communicate(std::move(readCallback), std::move(writeCallback));
713 void Subprocess::communicate(FdCallback readCallback,
714 FdCallback writeCallback) {
715 returnCode_.enforce(ProcessReturnCode::RUNNING);
718 std::vector<pollfd> fds;
719 fds.reserve(pipes_.size());
720 std::vector<int> toClose;
721 toClose.reserve(pipes_.size());
723 while (!pipes_.empty()) {
727 for (auto& p : pipes_) {
730 // Yes, backwards, PIPE_IN / PIPE_OUT are defined from the
731 // child's point of view.
733 // Still keeping fd in watched set so we get notified of POLLHUP /
736 } else if (p.direction == PIPE_IN) {
737 pfd.events = POLLOUT;
746 r = ::poll(fds.data(), fds.size(), -1);
747 } while (r == -1 && errno == EINTR);
748 checkUnixError(r, "poll");
750 for (int i = 0; i < pipes_.size(); ++i) {
752 DCHECK_EQ(fds[i].fd, p.parentFd);
753 short events = fds[i].revents;
756 if (events & POLLOUT) {
757 DCHECK(!(events & POLLIN));
758 if (writeCallback(p.parentFd, p.childFd)) {
759 toClose.push_back(i);
764 // Call read callback on POLLHUP, to give it a chance to read (and act
766 if (events & (POLLIN | POLLHUP)) {
767 DCHECK(!(events & POLLOUT));
768 if (readCallback(p.parentFd, p.childFd)) {
769 toClose.push_back(i);
774 if ((events & (POLLHUP | POLLERR)) && !closed) {
775 toClose.push_back(i);
780 // Close the fds in reverse order so the indexes hold after erase()
781 for (int idx : boost::adaptors::reverse(toClose)) {
782 auto pos = pipes_.begin() + idx;
783 closeChecked(pos->parentFd);
789 void Subprocess::enableNotifications(int childFd, bool enabled) {
790 pipes_[findByChildFd(childFd)].enabled = enabled;
793 bool Subprocess::notificationsEnabled(int childFd) const {
794 return pipes_[findByChildFd(childFd)].enabled;
797 int Subprocess::findByChildFd(int childFd) const {
798 auto pos = std::lower_bound(
799 pipes_.begin(), pipes_.end(), childFd,
800 [] (const PipeInfo& info, int fd) { return info.childFd < fd; });
801 if (pos == pipes_.end() || pos->childFd != childFd) {
802 throw std::invalid_argument(folly::to<std::string>(
803 "child fd not found ", childFd));
805 return pos - pipes_.begin();
808 void Subprocess::closeParentFd(int childFd) {
809 int idx = findByChildFd(childFd);
810 closeChecked(pipes_[idx].parentFd);
811 pipes_.erase(pipes_.begin() + idx);
819 // We like EPIPE, thanks.
820 ::signal(SIGPIPE, SIG_IGN);
824 Initializer initializer;